Java OOP Lab: Inheritance
Objective
To implement different types of inheritance in Java and understand how classes interact in
an object-oriented programming paradigm.
1. Single Inheritance
Create a base class and a derived class to demonstrate single inheritance.
// Base Class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Derived Class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Test Single Inheritance
public class SingleInheritanceTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Own method
}
}
2. Multilevel Inheritance
Add another level of inheritance to the above example.
// Base Class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Derived Class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Further Derived Class
class Puppy extends Dog {
void weep() {
System.out.println("The puppy weeps.");
}
}
// Test Multilevel Inheritance
public class MultilevelInheritanceTest {
public static void main(String[] args) {
Puppy puppy = new Puppy();
puppy.eat(); // Inherited from Animal
puppy.bark(); // Inherited from Dog
puppy.weep(); // Own method
}
}
3. Hierarchical Inheritance
Show how multiple classes inherit from the same base class.
// Base Class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Derived Class 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Derived Class 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
// Test Hierarchical Inheritance
public class HierarchicalInheritanceTest {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
cat.eat(); // Inherited method
cat.meow(); // Cat's own method
}
}
4. Hybrid Inheritance (Using Interfaces)
Since Java doesn’t support multiple inheritance with classes, use interfaces to simulate
hybrid inheritance.
// Interface 1
interface Animal {
void eat();
}
// Interface 2
interface Pet {
void play();
}
// Class implementing both interfaces
class Dog implements Animal, Pet {
public void eat() {
System.out.println("This dog eats food.");
}
public void play() {
System.out.println("The dog plays fetch.");
}
}
// Test Hybrid Inheritance
public class HybridInheritanceTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // From Animal interface
dog.play(); // From Pet interface
}
}