Relation_Inheritance1
 
  • Class A is super class of B and A
  • Class B and C are the subclasses of A
  • Class D is the subclass of A and B
 
Code snippet images :

Sub Class B extends Super-Class A

Class C extends super class A; Class D extends class B, and inherit both the (super) classes B and A.

Complete Cods :

import java.io.*;
import java.lang.reflect.*;
import java.util.*;

public class ClassTemplate1 {

public String str1; private String str2;
public ClassTemplate1() {
// TODO Auto-generated constructor stub
str2="encapsulated strictly Private scope";
System.out.println(str2);
}

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
try{
System.out.println(" Class B objects---");
B b1 = new B(20);
System.out.println(" Class C objects---");
C c1 = new C (40);
System.out.println(" Class D objects ---");
D d1 = new D (60);
System.out.println(b1.x1 + " "+c1.x1 + " " + d1.x1);

}catch(NumberFormatException e){
//
}
}
}
class A{
int x1 ;
A(){
System.out.println("superclass Constructor explicit A invoked");
} // explicit constructor
A(int n1){ // implicit constructor
x1 = n1;
System.out.println("Constructor implicit A invoked"
+ this.getClass());
System.out.println("----");
}
}


class B extends A{
int x1;
B(){
System.out.println("super class Constructor explicit B invoked");
} // explicit constructor
B(int n1){
x1 = n1;
System.out.println("Constructor implicit B invoked : super "
+ this.getClass().getSuperclass());
}
}

//
class C extends A{
int x1;
C(int n1){
x1 = n1;
System.out.println("Constructor Implicit C invoked : super "
+ this.getClass().getSuperclass());
System.out.println("secret number " +x1 );
}
}

 

class D extends B{
int x1;
Class superclass =this.getClass().getSuperclass();
Class localclass =this.getClass();

D(int n1){
x1 = n1;
System.out.println("Constructor cascade D invoked : super "
+ this.getClass().getSuperclass());
System.out.println("secret number " +x1 );

}


}
 

Runtime view and Output, note class D is linked to two super-classes