WORKSHEET – 3
Name : Branch : CSE
UID : Subject : Java lab
Question:
Program to learn different types of inheritance in java.
Code:
1). Single Inheritance
class Animal {
void eat() {
System.out.println("eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("barking...");
}
}
class TestInheritance {
public static void main(String args[]) {
Dog d = new Dog();
d.bark();
d.eat();
}
}
Output:
2). Multilevel Inheritance
class Animal {
void eat() {
System.out.println("eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("barking...");
}
}
class BabyDog extends Dog {
void weep() {
System.out.println("weeping...");
}
}
class TestInheritance2 {
public static void main(String args[]) {
BabyDog d = new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
3). Hierarchical Inheritance
class one {
public void print_geek() {
System.out.println("Geeks");
}
}
class two extends one {
public void print_for() {
System.out.println("for");
}
}
class three extends one {
/* ............ */
}
// Derived class
public class Main {
public static void main(String[] args) {
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}
Output:
4). Multiple Inheritance (using Interface)
interface one {
public void print_geek();
}
interface two {
public void print_for();
}
interface three extends one, two {
public void print_geek();
}
class child implements three {
@Override
public void print_geek() {
System.out.println("Geeks");
}
public void print_for() {
System.out.println("for");
}
}
// Derived class
public class Main {
public static void main(String[] args) {
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output: