Common java program which contains following concepts:
• Method Overriding (@Override)
• Abstract Class
• super Keyword (calling parent constructor and methods)
• final Keyword (prevents method overriding)
• Polymorphism (Dynamic Method Dispatch)
• Inheritance (extends) and Interface (implements)
You can write this program in all concepts of unit 3.1 and 3.2
// Define an interface
interface Animal {
void makeSound(); // Abstract method to be implemented
// Abstract class
abstract class LivingBeing {
// Constructor
LivingBeing() {
System.out.println("A living being is created.");
// Concrete method (can be overridden)
void breathe() {
System.out.println("Living being is breathing...");
// Final method (CANNOT be overridden)
final void grow() {
System.out.println("Living being is growing...");
// Abstract method (MUST be implemented by subclasses)
abstract void eat();
}
// Child class Dog extends LivingBeing and implements Animal
class Dog extends LivingBeing implements Animal {
// Constructor using super()
Dog() {
super(); // Calls parent constructor
System.out.println("A dog is created.");
// Overriding makeSound() from Animal interface
public void makeSound() {
System.out.println("Dog barks: Woof Woof!");
// Overriding breathe() from LivingBeing
@Override
void breathe() {
super.breathe(); // Calls parent method
System.out.println("Dog is breathing heavily...");
// Implementing abstract method eat()
@Override
void eat() {
System.out.println("Dog is eating dog food...");
// Main class demonstrating all concepts
public class AbstractExtendImplement {
public static void main(String[] args) {
// Polymorphism: Parent reference holding a child object
Animal myDog = new Dog();
myDog.makeSound(); // Calls Dog's version of makeSound()
// Using LivingBeing reference
LivingBeing lb = new Dog();
lb.breathe(); // Calls overridden breathe() method from Dog
lb.grow(); // Calls final method from LivingBeing (cannot be overridden)
lb.eat(); // Calls Dog's implementation of eat()