Inheritance

Inheritance
1) The mechanism of derriving one class from another class.
2) Aquiring the properties of one class to another class Types of Inheritance
  • Single Inheritance
  • Multilevel Inheritance

Single Inheritance

When a subclass is derived simply from it’s parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it’s parent class. It is also called single inheritance or one level inheritance.




Example:

class A {
void Show()
{
System.out.println(x);
}
}
class B extends A
{
public static void main(String args[])
{
A a = new A();
a.Show();
}
}

Multilevel Inheritance

It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it’s parent class and this parent class works as the child class for it’s just above ( parent ) class. Multilevel inheritance can go up to any number of level.

Example:
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”);
}
}

class C extends B{
void display(){
System.out.println(“C”);
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}

Java does not support multiple Inheritance

Multiple Inheritance

The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.

super keyword

The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java.

The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.

Example:
public class Superclass
{
public void printMethod()
{
System.out.println(“Printed in Superclass.”);
}
}

Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass
{ // overrides printMethod in Superclass
public void printMethod()
{
super.printMethod();
System.out.println(“Printed in Subclass”);
}
public static void main(String[] args)
{
Subclass s = new Subclass(); s.printMethod();
}
}

Welcome Back!

Login to your account below

Retrieve your password

Please enter your username or email address to reset your password.

error: Content is protected !!