150 likes | 299 Views
Object-Oriented Programming: Inheritance. Introduction. Inheritance Create new class from existing class Subclass extends super class. the keyword extends is used to derive a class in java. Simple and Multilevel Inheritance.
E N D
Introduction • Inheritance • Create new class from existing class • Subclass extends super class. the keyword extends is used to derive a class in java .
Simple and Multilevel Inheritance Simple Inheritance Multilevel Inheritance
Superclasses and subclasses • Example: • superclass: Vehicle • Cars, trucks, boats, bicycles, … • subclass: Car • Smaller, more-specific subset of vehicles
single inheritance or one level inheritance class A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); }}class B extends A{ public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } void display(){ System.out.println("B"); }}
Multilevel Inheritance class A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); }}class B extends A{ void Showb(){ System.out.println("B"); }}
The super keyword The super is java keyword is used to access the members of the super class. It is used for two purposes in java. • keyword super used to access the hidden data variables of the super class hidden by the sub class. super.member; Here member can either be an instance variable or a method
class A{ int a; float b; void Show(){ System.out.println("b in super class: " + b); }}class A{ int a; float b; void Show(){ System.out.println("b in super class: " + b); }}
Output: b in super class: 5.0 b in super class: 5.0 a in sub class: 1
2. The keyword super used to call super class constructor in the subclass. This functionality can be achieved just by using the following command. super(param-list); Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list. The following program illustrates the use of the super keyword to call a super class constructor. super()
class A{ int a; int b; int c; A(int p, int q, int r)class A{ int a; int b; int c; A(int p, int q, int r) { a=p; b=q; c=r; }}
Output: a = 4 b = 3 c = 8 d = 7