Week 5
Week 5
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.
Qn
1:
Create a hierarchy of animals with classes like Animal, Mammal, Bird, and Fish.
Implement polymorphism to demonstrate different animal sounds. Hint: Create an
abstract class Animal with an abstract method makeSound().
Create subclasses Mammal, Bird, and Fish, inheriting from Animal and overriding
the makeSound()
method. Create an array of Animal objects to store different types of animals.
Iterate through the array and call the makeSound()
method for each animal, demonstrating polymorphism.
void makeSound() {
void makeSound() {
System.out.println("Chirp!");
void makeSound() {
System.out.println("Blub!");
}
}
animal.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.
return a + b;
return a + b;
}
public int calculate(int a, int b, char operator) {
switch (operator) {
case '/':
if (b != 0) return a / b;
}
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).
class Animal {
this.name = name;
this.sound = sound;
this.numLegs = numLegs;
public Dog() {
public Cat() {
public Bird() {
super("Bird", "chirp", 2);
dog.makeSound();
dog.walk();
cat.makeSound();
cat.walk();
bird.makeSound();
bird.walk();
}
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