Last active
November 10, 2015 08:47
-
-
Save rishi93/b7f2ae88ed208e8e3dd7 to your computer and use it in GitHub Desktop.
Simple Inheritance Example in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* super.super is not allowed in Java. */ | |
import java.io.*; | |
class A | |
{ | |
private int a_data; | |
public A(int a_data) | |
{ | |
System.out.println("Class A constructor is called"); | |
this.a_data = a_data; | |
} | |
public void printdata() | |
{ | |
System.out.println(this.a_data); | |
} | |
} | |
class B extends A | |
{ | |
private int b_data; | |
public B(int b_data) | |
{ | |
super(0); /* B has all fields of A, and these fields need to be initialized */ | |
System.out.println("Class B constructor is called"); | |
this.b_data = b_data; | |
} | |
public void printdata() | |
{ | |
super.printdata(); | |
System.out.println(this.b_data); | |
} | |
} | |
class C extends B | |
{ | |
private int c_data; | |
public C(int c_data) | |
{ | |
super(1); | |
System.out.println("Class C constructor is called"); | |
this.c_data = c_data; | |
} | |
public void printdata() | |
{ | |
super.printdata(); | |
System.out.println(this.c_data); | |
} | |
} | |
class Ideone | |
{ | |
public static void main (String[] args) | |
{ | |
C ob = new C(5); | |
ob.printdata(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment