Inheritance Programs with Outputs
Program 1: Single Level Inheritance
class Animal {
Animal() {
[Link]("Parent class constructor");
}
void display() {
[Link]("I am from Animal class");
}
}
class Dog extends Animal {
Dog() {
[Link]("Child class constructor");
}
void bark() {
[Link]("Dog is barking");
}
}
public class SLI_Demo {
public static void main(String[] args) {
Dog ob = new Dog();
[Link]();
[Link]();
}
}
Output:
Parent class constructor
Child class constructor
I am from Animal class
Dog is barking
Program 2: Multi Level Inheritance
class Animal {
Animal() {
[Link]("Parent class constructor");
}
void display() {
[Link]("I am from Animal class");
}
}
class Dog extends Animal {
Dog() {
[Link]("Child class constructor");
}
void bark() {
[Link]("Dog is barking");
}
}
class BabyDog extends Dog {
BabyDog() {
[Link]("Baby Dog constructor");
}
void weep() {
[Link]("I am Baby Dog");
}
}
public class MLI_Demo {
public static void main(String[] args) {
BabyDog ob = new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Output:
Parent class constructor
Child class constructor
Baby Dog constructor
I am from Animal class
Dog is barking
I am Baby Dog
Program 3: Hierarchical Inheritance
class Animal {
void display() {
[Link]("This is Animal class");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
[Link]("Cat is meowing");
}
}
public class HI_Demo {
public static void main(String[] args) {
Dog ob1 = new Dog();
Cat ob2 = new Cat();
[Link]();
[Link]();
[Link]();
}
}
Output:
This is Animal class
Dog is barking
Cat is meowing
Program 4: Super Keyword
class Parent {
int m;
Parent(int z) {
m = z;
}
}
class Child extends Parent {
int m;
Child(int x, int y) {
super(x);
m = y;
}
void display() {
[Link]("m of Child: " + m);
[Link]("m of Parent: " + super.m);
}
}
public class Demo {
public static void main(String[] args) {
Child ob = new Child(100, 200);
[Link]();
}
}
Output:
m of Child: 200
m of Parent: 100
Program 5: Method Overriding
class Father {
void property() {
[Link]("I will give you money");
}
void marriage() {
[Link]("You marry XYZ girl");
}
}
class Son extends Father {
void marriage() {
[Link]("I will marry ABC girl");
}
}
public class OverrideDemo {
public static void main(String[] args) {
Son ob = new Son();
[Link]();
[Link]();
}
}
Output:
I will give you money
I will marry ABC girl