0% found this document useful (0 votes)
19 views

Week 5 Java

SRM week 5

Uploaded by

Lakshy Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Week 5 Java

SRM week 5

Uploaded by

Lakshy Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY

FACULTY OF ENGINERING AND TECHNOLOGY


SCHOOL OF COMPUTING
Department of Computing Technologies

[Assignment Week 2]
21CSC203P-ADVANCED PROGRAMMING PRACTICE

JULY–DECEMBER 2024

[RA2311003010291]
[SAVIO BINO]
[2nd/E1]
I. Abstraction:
Qn 1: Create an abstract class Animal with abstract methods make Sound() and eat().
Create subclasses Dog, Cat, and Bird that inherit from Animal and implement the abstract
methods accordingly.

CODE-
abstract class Animal {
abstract void makeSound();
abstract void eat();
}

class Dog extends Animal {


void makeSound() {
System.out.println("Bark");
}

void eat() {
System.out.println("Dog is eating");
}
}

class Cat extends Animal {


void makeSound() {
System.out.println("Meow");
}

void eat() {
System.out.println("Cat is eating");
}
}

class Bird extends Animal {


void makeSound() {
System.out.println("Chirp");
}

void eat() {
System.out.println("Bird is eating");
}
}

public class Main {


public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound();
dog.eat();

Animal cat = new Cat();


cat.makeSound();
cat.eat();

Animal bird = new Bird();


bird.makeSound();
bird.eat();
}
}

Qn 2: Create an abstract class Shape with abstract methods calculateArea() and


calculatePerimeter(). Create subclasses Circle, Rectangle, and Triangle that inherit from
Shape and implement the abstract methods accordingly.

CODE-
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

double calculateArea() {
return Math.PI * radius * radius;
}

double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Rectangle extends Shape {


double length, width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

double calculateArea() {
return length * width;
}

double calculatePerimeter() {
return 2 * (length + width);
}
}

class Triangle extends Shape {


double a, b, c; // sides of the triangle

Triangle(double a, double b, double c) {


this.a = a;
this.b = b;
this.c = c;
}

double calculateArea() {
double s = (a + b + c) / 2; // semi-perimeter
return Math.sqrt(s * (s - a) * (s - b) * (s - c)); // Heron's formula
}

double calculatePerimeter() {
return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Shape circle = new Circle(5);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

Shape rectangle = new Rectangle(4, 6);


System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());

Shape triangle = new Triangle(3, 4, 5);


System.out.println("Triangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}

Qn 3: Create an abstract class Employee with abstract methods calculateSalary() and


getEmployeeDetails(). Create subclasses RegularEmployee, ContractEmployee, and
HourlyEmployee that inherit from Employee and implement the abstract methods
Accordingly

CODE-
abstract class Employee {
String name;
int id;

Employee(String name, int id) {


this.name = name;
this.id = id;
}

abstract double calculateSalary();


abstract String getEmployeeDetails();
}

class RegularEmployee extends Employee {


double basicSalary, bonus;

RegularEmployee(String name, int id, double basicSalary, double bonus) {


super(name, id);
this.basicSalary = basicSalary;
this.bonus = bonus;
}

double calculateSalary() {
return basicSalary + bonus;
}

String getEmployeeDetails() {
return "Regular Employee - Name: " + name + ", ID: " + id;
}
}

class ContractEmployee extends Employee {


double contractAmount;

ContractEmployee(String name, int id, double contractAmount) {


super(name, id);
this.contractAmount = contractAmount;
}

double calculateSalary() {
return contractAmount;
}

String getEmployeeDetails() {
return "Contract Employee - Name: " + name + ", ID: " + id;
}
}

class HourlyEmployee extends Employee {


double hourlyRate;
int hoursWorked;

HourlyEmployee(String name, int id, double hourlyRate, int hoursWorked) {


super(name, id);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}

double calculateSalary() {
return hourlyRate * hoursWorked;
}

String getEmployeeDetails() {
return "Hourly Employee - Name: " + name + ", ID: " + id;
}
}

public class Main {


public static void main(String[] args) {
Employee regEmp = new RegularEmployee("John", 101, 50000, 5000);
System.out.println(regEmp.getEmployeeDetails());
System.out.println("Salary: " + regEmp.calculateSalary());

Employee contractEmp = new ContractEmployee("Jane", 102, 60000);


System.out.println(contractEmp.getEmployeeDetails());
System.out.println("Salary: " + contractEmp.calculateSalary());

Employee hourlyEmp = new HourlyEmployee("Mark", 103, 20, 160);


System.out.println(hourlyEmp.getEmployeeDetails());
System.out.println("Salary: " + hourlyEmp.calculateSalary());
}
}

II.Polymorphism:
Qn 1: Create a hierarchy of animals with classes like Animal, Mammal, Bird, and Fish.
Implement polymorphism to demonstrate different animal sounds.

CODE-
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Mammal extends Animal {


@Override
void makeSound() {
System.out.println("Mammal sound");
}
}

class Bird extends Animal {


@Override
void makeSound() {
System.out.println("Chirp Chirp");
}
}

class Fish extends Animal {


@Override
void makeSound() {
System.out.println("Glub Glub");
}
}

class Dog extends Mammal {


@Override
void makeSound() {
System.out.println("Bark");
}
}

class Cat extends Mammal {


@Override
void makeSound() {
System.out.println("Meow");
}
}

public class Main {


public static void main(String[] args) {
Animal genericAnimal = new Animal();
Animal mammal = new Mammal();
Animal bird = new Bird();
Animal fish = new Fish();
Animal dog = new Dog();
Animal cat = new Cat();

genericAnimal.makeSound();
mammal.makeSound();
bird.makeSound();
fish.makeSound();
dog.makeSound();
cat.makeSound();
}
}

Qn 2: Overload
Create a Calculator class with multiple calculate () methods that take different
combinations of arguments (e.g., calculate (int, int), calculate (double, double), calculate
(int, int, char)). Implement these methods to perform different arithmetic operations based
on the arguments.
CODE-
class Calculator {

int calculate(int a, int b) {


return a + b;
}

double calculate(double a, double b) {


return a * b;
}

int calculate(int a, int b, char operator) {


switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0)
return a / b;
else
throw new ArithmeticException("Cannot divide by zero");
default:
throw new IllegalArgumentException("Invalid operator");
}
}

double calculate(double a, double b, char operator) {


switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0.0)
return a / b;
else
throw new ArithmeticException("Cannot divide by zero");
default:
throw new IllegalArgumentException("Invalid operator");
}
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();

System.out.println("Addition (int): " + calc.calculate(10, 5));


System.out.println("Multiplication (double): " + calc.calculate(5.5, 4.0));
System.out.println("Subtraction (int, with operator '-'): " + calc.calculate(15, 8, '-'));
System.out.println("Division (double, with operator '/'): " + calc.calculate(20.0, 4.0, '/'));
}
}

Qn 3: Override
Create a base class Calculator with a calculate () method that takes two double arguments.
Implement this method to perform addition. Create subclasses SubtractionCalculator,
MultiplicationCalculator, and DivisionCalculator that inherit from Calculator and override
the calculate () method to perform their respective arithmetic operations.

CODE-
class Calculator {
double calculate(double a, double b) {
return a + b;
}
}

class SubtractionCalculator extends Calculator {


@Override
double calculate(double a, double b) {
return a - b;
}
}

class MultiplicationCalculator extends Calculator {


@Override
double calculate(double a, double b) {
return a * b;
}
}

class DivisionCalculator extends Calculator {


@Override
double calculate(double a, double b) {
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("Cannot divide by zero");
}
}
}

public class Main {


public static void main(String[] args) {
Calculator addCalc = new Calculator();
Calculator subCalc = new SubtractionCalculator();
Calculator mulCalc = new MultiplicationCalculator();
Calculator divCalc = new DivisionCalculator();

System.out.println("Addition: " + addCalc.calculate(10, 5));


System.out.println("Subtraction: " + subCalc.calculate(10, 5));
System.out.println("Multiplication: " + mulCalc.calculate(10, 5));
System.out.println("Division: " + divCalc.calculate(10, 5));
}
}

III. Inheritance:

Qn 1: Base Class: Animal


➢ Attributes: name, sound, num_legs
➢ Methods: make_sound(), walk()
Derived Classes:
➢ Dog: barks
➢ Cat: meows
➢ Bird: chirps, flies
Questions:
1. Create a base class Animal with the specified attributes and methods.
2. Create derived classes Dog, Cat, and Bird that inherit from Animal.
3. Override the make_sound() and walk() methods in each derived class to provide specific
implementations.
4. Create objects of each derived class and demonstrate their behavior (e.g., call
make_sound() and walk() methods).

CODE-
// Base class Animal
class Animal {
String name;
String sound;
int num_legs;

Animal(String name, String sound, int num_legs) {


this.name = name;
this.sound = sound;
this.num_legs = num_legs;
}

void make_sound() {
System.out.println(name + " makes a sound: " + sound);
}

void walk() {
System.out.println(name + " walks on " + num_legs + " legs.");
}
}

// Derived class Dog


class Dog extends Animal {

Dog(String name) {
super(name, "Bark", 4);
}

@Override
void make_sound() {
System.out.println(name + " barks: " + sound);
}

@Override
void walk() {
System.out.println(name + " walks on " + num_legs + " legs, wagging its tail.");
}
}

// Derived class Cat


class Cat extends Animal {

Cat(String name) {
super(name, "Meow", 4);
}

@Override
void make_sound() {
System.out.println(name + " meows: " + sound);
}

@Override
void walk() {
System.out.println(name + " walks on " + num_legs + " legs gracefully.");
}
}

// Derived class Bird


class Bird extends Animal {

Bird(String name) {
super(name, "Chirp", 2);
}

@Override
void make_sound() {
System.out.println(name + " chirps: " + sound);
}

@Override
void walk() {
System.out.println(name + " hops on " + num_legs + " legs and flies.");
}
}

public class Main {


public static void main(String[] args) {
Animal dog = new Dog("Buddy");
dog.make_sound();
dog.walk();

Animal cat = new Cat("Whiskers");


cat.make_sound();
cat.walk();

Animal bird = new Bird("Tweety");


bird.make_sound();
bird.walk();
}
}

Qn 2: Consider a vehicle hierarchy with a base class Vehicle that has attributes like make,
model, year, and num_wheels. We want to create derived classes Car, Truck, and Motorcycle
that inherit from Vehicle and have additional specific attributes and methods. Additionally, we
want to introduce another base class Engine with attributes like type, horsepower, and
fuel_type, and have Car, Truck, and Motorcycle inherit from both Vehicle and
Engine.Implement using multiple inheritance.

CODE-
// Base class Vehicle
class Vehicle {
String make;
String model;
int year;
int num_wheels;

Vehicle(String make, String model, int year, int num_wheels) {


this.make = make;
this.model = model;
this.year = year;
this.num_wheels = num_wheels;
}

void displayInfo() {
System.out.println("Make: " + make + ", Model: " + model + ", Year: " + year + ", Wheels: " +
num_wheels);
}
}

// Interface Engine
interface Engine {
String type = "Unknown"; // default type
int horsepower = 0; // default horsepower
String fuel_type = "Unknown"; // default fuel type

void engineDetails(); // Abstract method to be implemented by classes


}

// Derived class Car


class Car extends Vehicle implements Engine {
int horsepower;
String fuel_type;

Car(String make, String model, int year, int horsepower, String fuel_type) {
super(make, model, year, 4); // Cars have 4 wheels
this.horsepower = horsepower;
this.fuel_type = fuel_type;
}

@Override
public void engineDetails() {
System.out.println("Engine Type: Petrol, Horsepower: " + horsepower + ", Fuel Type: " + fuel_type);
}
}

// Derived class Truck


class Truck extends Vehicle implements Engine {
int horsepower;
String fuel_type;

Truck(String make, String model, int year, int horsepower, String fuel_type) {
super(make, model, year, 6); // Trucks have 6 wheels
this.horsepower = horsepower;
this.fuel_type = fuel_type;
}

@Override
public void engineDetails() {
System.out.println("Engine Type: Diesel, Horsepower: " + horsepower + ", Fuel Type: " + fuel_type);
}
}

// Derived class Motorcycle


class Motorcycle extends Vehicle implements Engine {
int horsepower;
String fuel_type;

Motorcycle(String make, String model, int year, int horsepower, String fuel_type) {
super(make, model, year, 2); // Motorcycles have 2 wheels
this.horsepower = horsepower;
this.fuel_type = fuel_type;
}

@Override
public void engineDetails() {
System.out.println("Engine Type: Electric, Horsepower: " + horsepower + ", Fuel Type: " + fuel_type);
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car("Toyota", "Corolla", 2022, 150, "Petrol");
Truck truck = new Truck("Ford", "F-150", 2023, 400, "Diesel");
Motorcycle motorcycle = new Motorcycle("Harley", "Iron 883", 2021, 80, "Electric");

car.displayInfo();
car.engineDetails();

truck.displayInfo();
truck.engineDetails();

motorcycle.displayInfo();
motorcycle.engineDetails();
}
}

IV.Encapsulation
Qn 1: A bank wants to create a class to represent bank accounts. Each account should have a
unique account number, an initial balance, and methods to deposit and withdraw funds. The
bank wants to ensure that the account balance is always positive and that withdrawals do not
exceed the balance.
➢ Create a class named BankAccount with private attributes for accountNumber, balance,
and a constant for the minimum balance allowed.
➢ Implement public getter and setter methods for the accountNumber attribute.
➢ Implement public methods deposit and withdraw that update the balance appropriately,
ensuring that the balance remains positive and that withdrawals do not exceed the
balance.

CODE-
class BankAccount {
private String accountNumber;
private double balance;
private final double MIN_BALANCE = 0.0;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
if (initialBalance >= MIN_BALANCE) {
this.balance = initialBalance;
} else {
this.balance = MIN_BALANCE;
}
}

// Getter for accountNumber


public String getAccountNumber() {
return accountNumber;
}

// Setter for accountNumber


public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}

// Method to deposit funds


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Successfully deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}

// Method to withdraw funds


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Successfully withdrew: " + amount);
} else if (amount > balance) {
System.out.println("Insufficient balance. Withdrawal denied.");
} else {
System.out.println("Withdrawal amount must be positive.");
}
}

// Method to display the balance


public double getBalance() {
return balance;
}
}

public class Main {


public static void main(String[] args) {
// Create a bank account with an initial balance of 500
BankAccount account = new BankAccount("123456789", 500.0);

// Display account number and initial balance


System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Initial Balance: " + account.getBalance());

// Deposit funds
account.deposit(150.0);
System.out.println("Balance after deposit: " + account.getBalance());

// Withdraw funds
account.withdraw(200.0);
System.out.println("Balance after withdrawal: " + account.getBalance());

// Try to withdraw more than available balance


account.withdraw(600.0);
System.out.println("Final Balance: " + account.getBalance());
}
}

Qn 2: Write a Java program to create a class called Rectangle with private instance variables
length and width. Provide public getter and setter methods to access and modify these
variables.

CODE-
class Rectangle {
private double length;
private double width;

// Constructor to initialize length and width


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Getter for length


public double getLength() {
return length;
}

// Setter for length


public void setLength(double length) {
if (length > 0) {
this.length = length;
} else {
System.out.println("Length must be positive.");
}
}
// Getter for width
public double getWidth() {
return width;
}

// Setter for width


public void setWidth(double width) {
if (width > 0) {
this.width = width;
} else {
System.out.println("Width must be positive.");
}
}

// Method to calculate the area of the rectangle


public double calculateArea() {
return length * width;
}

// Method to calculate the perimeter of the rectangle


public double calculatePerimeter() {
return 2 * (length + width);
}
}

public class Main {


public static void main(String[] args) {
// Create a Rectangle object
Rectangle rect = new Rectangle(5.0, 3.0);

// Display initial length and width


System.out.println("Length: " + rect.getLength());
System.out.println("Width: " + rect.getWidth());

// Display area and perimeter


System.out.println("Area: " + rect.calculateArea());
System.out.println("Perimeter: " + rect.calculatePerimeter());

// Modify length and width


rect.setLength(7.0);
rect.setWidth(4.0);

// Display updated length and width


System.out.println("Updated Length: " + rect.getLength());
System.out.println("Updated Width: " + rect.getWidth());

// Display updated area and perimeter


System.out.println("Updated Area: " + rect.calculateArea());
System.out.println("Updated Perimeter: " + rect.calculatePerimeter());
}
}

You might also like