extends keyword is used to define a subclass.super() keyword is used to explicitly call a superclass constructor.Inheritance is used in scenarios where a class needs to share attributes and behaviors with another class. Common use cases include:
class Animal { public void makeSound() { System.out.println("This animal makes a sound."); }}class Cat extends Animal { public void makeSound() { System.out.println("The cat meows."); } public void purr() { System.out.println("The cat purrs."); }}class TestPolymorphism { public static void main(String[] args) { Animal myAnimal = new Cat(); // Parent reference to Child object myAnimal.makeSound(); // Calls the overridden method in Cat class // myAnimal.purr(); // This line would cause a compile-time error Cat myCat = (Cat) myAnimal; // Downcasting myCat.purr(); // Now we can call the method specific to Cat class }}The cat meows.
The cat purrs.Inheritance of Methods and Properties:
Animal) has, they are by default available to the child class (Cat). This means that with a child class reference, you can call both parent and child class methods.Method Availability:
Cat) has that are not in the parent class (Animal), cannot be called with a parent class reference. This means you can't call purr using an Animal reference, even if it refers to a Cat object.Parent Reference Holding Child Object:
A parent class reference can be used to hold a child object, but child class reference cannot be used to hold parent class objects. However, by using the parent class reference, you can't call child class-specific methods but can call all methods available in the parent class. This is because the reference type determines what methods can be called.
Animal myAnimal = new Cat(); // Parent reference to Child object
myAnimal.purr(); // This line would cause a compile-time errorMethod Overriding and Polymorphism:
When a method is overridden in the child class, calling that method on a parent reference pointing to a child object will invoke the child class's overridden method. This demonstrates runtime polymorphism.
Animal myAnimal = new Cat(); // Parent reference to Child object
myAnimal.makeSound(); // Calls the overridden method in Cat classIn this example, we demonstrate the concept of using a parent class reference to refer to a child class object.
xxxxxxxxxxclass Animal { protected String name; public void eat() { System.out.println("This animal eats food."); } public void sleep() { System.out.println("This animal sleeps."); }}class Dog extends Animal { public void bark() { System.out.println("The dog barks."); } public void eat() { System.out.println("The dog eats bones."); }}public class TestInheritance { public static void main(String[] args) { Dog dog = new Dog(); dog.name = "Buddy"; dog.eat(); // Calls the overridden method in Dog class dog.sleep(); // Inherited method from Animal class dog.bark(); // Method specific to Dog class }}The dog eats bones.
This animal sleeps.
The dog barks.