Posted in

INHERITANCE PROGRAMS AND ALGORITHMS IN JAVA

1. Write a simple Java program to demonstrate inheritance create a Vehicle class with basic properties like speed and color and create a Car class that inherits from Vehicle and adds a new property, like model. Show how inheritance allows the Car class to reuse properties and methods of the Vehicle class?

Algorithm :

  • Start the program.
  • Define a class Vehicle with attributes color and speed.
  • Create a constructor in Vehicle to initialize color and speed.
  • Define a method displayInfo() in Vehicle to print color and speed.
  • Create a subclass Car that extends Vehicle and adds a model attribute.
  • Create a constructor in Car that calls the Vehicle constructor using super() and initializes model.
  • Override the displayInfo() method in Car:
    • First call super.displayInfo() to print color and speed.
    • Then print the model.
  • In the main() method:
    • Create a Car object with specified color, speed, and model.
    • Call displayInfo() to output all properties.
  • End the program.

Program :

class Vehicle {
    String color;
    int speed;
    Vehicle(String color, int speed) {
        this.color = color;
        this.speed = speed;
    }
    void displayInfo() {
        System.out.println(“Color: ” + color + “, Speed: ” + speed);
    }
}
class Car extends Vehicle {
    String model;
    Car(String color, int speed, String model) {
        super(color, speed);  // Calling the superclass constructor
        this.model = model;
    }
    void displayInfo() {
        super.displayInfo();
        System.out.println(“Model: ” + model);
    }
    public static void main(String[] args) {
        Car car = new Car(“Red”, 120, “Tesla Model S”);
        car.displayInfo();  // Output all properties of the car
    }
}

Output : 

Color: Red, Speed: 120
Model: Tesla Model S

Explanation :

This program demonstrates inheritance and method overriding in Java. The Vehicle class holds common properties like color and speed, while Car extends it by adding a specific model. The Car constructor uses super() to reuse the Vehicle constructor, ensuring code reuse and clarity. The displayInfo() method in Car overrides the base method and calls super.displayInfo() to show inherited details before printing the model. This showcases how subclasses can extend and customize superclass behavior efficiently.

2. Write a Java program to demonstrate method overriding create a Shape class with a method area() and create two subclasses: Circle and Rectangle, each overriding the area() method to calculate and return the    area specific to the shape?

Algorithm :

  • Start the program.
  • Create a base class Shape with a method area() that prints “Area of Shape”.
  • Create a subclass Circle that overrides the area() method to print “Area of Circle”.
  • Create another subclass Rectangle that overrides the area() method to print “Area of Rectangle”.
  • In the main() method:
  • Create a Shape reference s1 pointing to a Circle object.
  • Create another Shape reference s2 pointing to a Rectangle object.
  • Call area() using s1.
  • Call area() using s2.
  • End the program.

Program :

class Shape {
    void area() {
        System.out.println(“Area of Shape”);
    }
}
class Circle extends Shape {
    void area() {
        System.out.println(“Area of Circle”);
    }
}
class Rectangle extends Shape {
    void area() {
        System.out.println(“Area of Rectangle”);
    }
}
public class Main {
    public static void main(String[] args) {
        Shape s1 = new Circle();
        Shape s2 = new Rectangle();
        s1.area(); 
        s2.area(); 
    }
}

Output :

Area of Circle
Area of Rectangle

Explanation :

          This program demonstrates method overriding and runtime polymorphism. The Shape class provides a general area() method, which is overridden in Circle and Rectangle to provide specific behavior. In the main method, the Shape references point to Circle and Rectangle objects. When the area() method is called, Java determines at runtime which version to execute based on the actual object, showcasing dynamic method dispatch.

3. Write a Java program to demonstrate the use of super() keyword create a base class Animal with a constructor that takes the animal’s name and create a derived class Dog that calls the super() method to pass the name to the Animal constructor?

Algorithm :

  • Start the program.
  • Define a class Animal with a constructor that takes a name parameter and prints “Animal constructor: ” followed by the name.
  • Create a subclass Dog that extends Animal.
  • In the Dog constructor, call the super(name) to invoke the Animal constructor.
  • After calling the superclass constructor, print “Dog constructor: ” followed by the name.
  • In the main() method, create a Dog object with the name “Buddy”.
  • The constructors execute in order: Animal first, then Dog.
  • End the program.

Program :

class Animal {
    String name;
    Animal(String name) {
        this.name = name;
        System.out.println(“Animal constructor: ” + name);
    }
}
class Dog extends Animal {
    Dog(String name) {
        super(name);  // Calling Animal’s constructor
        System.out.println(“Dog constructor: ” + name);
    }
    public static void main(String[] args) {
        Dog dog = new Dog(“Buddy”);
    }
}

Output :

Animal constructor: Buddy
Dog constructor: Buddy

Explanation :

                    This program illustrates constructor chaining using inheritance. When a Dog object is created, the Dog constructor calls the Animal constructor using super(name). This ensures that the parent class is properly initialized before executing the child class’s constructor. The output confirms that the Animal constructor runs first, followed by the Dog constructor, showing the top-down flow of constructor execution in inheritance.

4. Write a Java program where a subclass inherits from a superclass and has its own methods create a class Person with properties like name and age and create a subclass Employee that inherits Person and adds a property salary?

Algorithm :

  • Start the program.
  • Define a class Person with name and age attributes.
  • Create a constructor in Person to initialize name and age.
  • Define a method display() in Person to print name and age.
  • Define a subclass Employee that extends Person and adds a salary attribute.
  • Create a constructor in Employee that calls super(name, age) to initialize the parent class fields, and sets the salary.
  • Override the display() method in Employee:
    • Call super.display() to print name and age.
    • Then print the salary.
  • In the main() method, create an Employee object with name “John”, age 30, and salary 50000.
  • Call the display() method on the Employee object.
  • End the program.

Program :

class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    void display() {
        System.out.println(“Name: ” + name + “, Age: ” + age);
    }
}
class Employee extends Person {
    double salary;
    Employee(String name, int age, double salary) {
        super(name, age);  // Calling Person’s constructor
        this.salary = salary;
    }
    void display() {
        super.display();  // Calling Person’s display method
        System.out.println(“Salary: ” + salary);
    }
    public static void main(String[] args) {
        Employee emp = new Employee(“John”, 30, 50000);
        emp.display();
    }
}

Output :

Name: John, Age: 30
Salary: 50000.0

Explanation :

This program showcases inheritance, constructor chaining, and method overriding. The Employee class inherits properties from the Person class and adds a salary attribute. When an Employee object is created, the Person constructor is called using super() to initialize common properties. The display() method is overridden in Employee to first call the base method for name and age, and then print the salary. This approach promotes code reuse and clean extension of class behavior.

5. Write a program to create a Java program that demonstrates constructor chaining in inheritance and  create a Base class with a constructor and create a Derived class that calls the constructor of the Base class using super()?

Algorithm :

  • Start the program.
  • Define a class Parent with a method greet() that prints “Hello from Parent class”.
  • Create a subclass Child that extends Parent.
  • In the Child class, override the greet() method.
  • Inside the overridden method, call super.greet() to invoke the parent class’s greet() method.
  • Then print “Hello from Child class”.
  • In the main() method, create an object of type Child.
  • Call the greet() method on this object.
  • Both the parent and child messages are printed.
  • End the program.

Program :

 class Parent {
    void greet() {
        System.out.println(“Hello from Parent class”);
    }
}
class Child extends Parent {
    void greet() {
        super.greet();  // Calling Parent’s greet method
        System.out.println(“Hello from Child class”);
    }
    public static void main(String[] args) {
        Child child = new Child();
        child.greet();
    }
}

Output :

Hello from Parent class
Hello from Child class

Explanation :

This program demonstrates method overriding and the use of super to call a superclass method. The Child class overrides the greet() method from the Parent class but still uses super.greet() to include the parent’s greeting before adding its own. This allows the subclass to extend or customize behavior without completely replacing the parent method. The output confirms that both messages are displayed in order, showcasing inheritance and method extension.

6. Write a Java program that demonstrates the concept of upcasting and downcasting and create a base class Animal and subclasses Cat and Dog.Demonstrate how upcasting and downcasting work when assigning an object of the derived class to a variable of the base class type?

Algorithm :

  • Start the program.
  • Define a base class Animal with a method sound() that prints “Animal makes a sound”.
  • Create a subclass Dog that overrides sound() to print “Dog barks”.
  • Create another subclass Cat that overrides sound() to print “Cat meows”.
  • In the main() method, declare an Animal reference animal1 and assign it a new Dog object (upcasting).
  • Declare another Animal reference animal2 and assign it a new Cat object (also upcasting).
  • Call sound() on both animal1 and animal2; polymorphism ensures the correct subclass method is called.
  • Downcast animal1 back to a Dog type and assign it to a Dog variable named dog.
  • Call sound() on dog again, which prints “Dog barks”.
  • End the program.

Program :

class Animal {
    void sound() {
        System.out.println(“Animal makes a sound”);
    }
}
class Dog extends Animal {
    @Override
    void sound() {
        System.out.println(“Dog barks”);
    }
}
class Cat extends Animal {
    @Override
    void sound() {
        System.out.println(“Cat meows”);
    }
}
public class Main {
    public static void main(String[] args) {
        // Upcasting: Dog object assigned to Animal reference
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();
        animal1.sound(); 
        animal2.sound();
        // Downcasting: Animal reference back to Dog
        Dog dog = (Dog) animal1;
        dog.sound(); 
    }
}

Output :  

Dog barks
Cat meows
Dog barks

Explanation :

This program demonstrates polymorphism, method overriding, upcasting, and downcasting. The Dog and Cat classes override the sound() method of the Animal superclass. When Animal references point to Dog or Cat objects (upcasting), the overridden methods are executed due to runtime polymorphism. The program also shows downcasting, where the Animal reference is cast back to a Dog object, allowing access to Dog-specific behavior. This illustrates how Java handles object types and dynamic method dispatch.

7. Write a Java program that demonstrates the use of abstract classes and interfaces in inheritance and create an abstract class Shape with an abstract method draw().create an interface Colorable with a method color() implement a class Circle that extends Shape and implements Colorable, providing implementations for both draw() and color() methods?

Algorithm :

  • Start the program.
  • Declare an abstract class Shape with an abstract method draw().
  • Declare an interface Colorable with an abstract method color().
  • Define a class Circle that:
    • Inherits from Shape.
    • Implements Colorable.
    • Provides implementation for both draw() and color() methods.
  •  In the main() method:
    • Create an object of Circle.
    • Call the draw() method on the Circle object.
    • Call the color() method on the Circle object.
  • End the program.

Program :

abstract class Shape {
    abstract void draw();
}
interface Colorable {
    void color();
}
class Circle extends Shape implements Colorable {
    @Override
    void draw() {
        System.out.println(“Drawing a Circle”);
    }
    @Override
    public void color() {
        System.out.println(“Coloring the Circle”);
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating a Circle object and calling methods
        Circle circle = new Circle();
        circle.draw();  // Calling abstract method
        circle.color(); // Calling interface method
    }
}

Output :

Drawing a Circle
Coloring the Circle

Explanation :

                 This program demonstrates the use of abstraction through an abstract class and interface implementation. The Shape class defines an abstract method draw(), while the Colorable interface defines a color() method. The Circle class extends Shape and implements Colorable, providing concrete implementations for both methods. In the main() method, a Circle object is created and both its draw() and color() methods are called, showcasing how a class can inherit from an abstract class and implement an interface simultaneously.

8. Write a Java program to implement a “has-a” and “is-a” relationship using inheritance and create a class Engine and a class Car that “has a” Engine and create a class Vehicle that “is a” Car (inheritance), and demonstrate both relationships with the appropriate object creation and method calls?

Algorithm :

  • Start
    • Define the Engine class with a method start() that prints a message.
    • Define the Car class that has a member of type Engine (composition).
    • In the Car constructor, initialize the engine object.
  • Create a drive() method in Car that:
    • Prints a driving message.
    • Calls the start() method of engine.
  • Define a Vehicle class that extends Car (inheritance).
  • Add a display() method in Vehicle to print a message.
  •  In the main() method:
    • Create an object of Car and call drive().
    • Create an object of Vehicle, then call drive() and display().
  • End

Program :

  class Engine {
    void start() {
        System.out.println(“Engine started.”);
    }
}
class Car {
    Engine engine;  // “has-a” relationship with Engine
    Car() {
        engine = new Engine();  // Creating an Engine object inside Car
    }
    void drive() {
        System.out.println(“Car is driving.”);
        engine.start();  // Calling Engine’s method
    }
}
class Vehicle extends Car {
    void display() {
        System.out.println(“This is a Vehicle.”);
    }
}
public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.drive();  // Car “has-a” Engine and uses it to start
        Vehicle myVehicle = new Vehicle();
        myVehicle.drive();  // Vehicle “is a” Car, so it can call Car’s methods
        myVehicle.display(); // Calling Vehicle specific method
    }
}

Output :

  Car is driving.
  Engine started.
  Car is driving.
  Engine started.
  This is a Vehicle.

Explanation :

               This program demonstrates composition and inheritance. The Car class has a “has-a” relationship with the Engine class by containing an Engine object and using its start() method inside drive(). The Vehicle class extends Car, forming an “is-a” relationship and inheriting the drive() method. In the main() method, both Car and Vehicle objects are created. The Car uses the engine to start while driving, and the Vehicle inherits this behavior and also includes its own method display(). This shows how object-oriented principles like reuse and modularity are achieved.

9. Write a Java program that demonstrates the use of super to call a method from a parent class that is overridden in a subclass and create a base class Animal with a method sound().create a Dog class that overrides sound(). In the Dog class, use super.sound() to call the base class method?

Algorithm :

  • Start
  • Define the Animal class with a method sound() that prints “Animal makes a sound.”
  • Create a subclass Dog that extends Animal.
  • Override the sound() method in Dog to:
    • Print “Dog barks.”
    • Call super.sound() to invoke the Animal class’s sound() method.
  • In the main() method:
    • Create an object of Dog.
    • Call the sound() method using the Dog object.
  • End

Program :

    class Animal {
    void sound() {
        System.out.println(“Animal makes a sound.”);
    }
}
class Dog extends Animal {
    @Override
    void sound() {
        System.out.println(“Dog barks.”);
        super.sound(); 
    }
}
public class Main {
    public static void main(String[] args) {
        // Creating an object of Dog class
        Dog dog = new Dog();
        dog.sound(); 
    }
}

Output :

Dog barks.
Animal makes a sound.

Explanation :

This program demonstrates method overriding and the use of the super keyword in Java. The Dog class extends the Animal class and overrides its sound() method to provide its own implementation. However, it also calls the parent class’s method using super.sound() to retain and reuse the base class behavior. When the Dog object calls sound(), it first prints “Dog barks.” and then “Animal makes a sound.”, showing both subclass and superclass behavior together.

10. Write a Java program to demonstrate the concept of polymorphism with inheritance and create a class Employee with a method work().create subclasses Manager and Developer, both overriding work() to provide specific implementations.Demonstrate how polymorphism allows you to call the appropriate work() method at runtime?

Algorithm :

  • Start
  • Define the Employee class with a method work() that prints “Employee is working.”.
  • Create a subclass Manager that extends Employee and overrides the work() method to print “Manager is managing the team.”.
  • Create another subclass Developer that also extends Employee and overrides the work() method to print “Developer is writing code.”.
  • In the main() method:
  • Create an Employee reference and assign it a new Manager object (emp1).
  • Create another Employee reference and assign it a new Developer object (emp2).
  • Call emp1.work() and emp2.work().
  • End

Program :

class Employee {
    void work() {
        System.out.println(“Employee is working.”);
    }
}
class Manager extends Employee {
    @Override
    void work() {
        System.out.println(“Manager is managing the team.”);
    }
}
class Developer extends Employee {
    @Override
    void work() {
        System.out.println(“Developer is writing code.”);
    }
}
public class Main {
    public static void main(String[] args) {
        Employee emp1 = new Manager(); 
        Employee emp2 = new Developer(); 
        emp1.work();
        emp2.work(); 
    }
}

Output :

  Manager is managing the team.
  Developer is writing code.

Explanation :

This program demonstrates runtime polymorphism through method overriding in Java. The Employee class provides a generic work() method. The Manager and Developer classes override this method to provide specific behavior. At runtime, although emp1 and emp2 are declared as Employee types, they refer to Manager and Developer objects respectively. Hence, calling work() on them executes the overridden version in their respective classes. This shows how Java determines the correct method to run based on the actual object type, not the reference type, which is a core principle of polymorphism.

Leave a Reply

Your email address will not be published. Required fields are marked *