Inheritance in java || What is inheritance in java? || Example of inheritance in java. || Explain inheritance in java || Explain Inheritance.


Inheritance

A class that is inherited is called a super class. The class that does the inheriting is called a subclass. To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. Being a super class for a subclass does not mean that the super class cannot be used by itself. You can only specify one super class for any subclass that you create. Java does not support the inheritance of multiple super classes into a single subclass. No class can be a super class of itself.

A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including sub classes. Constructors are called in order of derivation.

Syntax:


class subclass-name extends superclass-name {

// body of class

}

Example:

class Vehicle //super class

{

int Wheels;

}

class Car extends Vehicle //subclass of Vehicle

{

void showCarWheels()

{

System.out.println("Car has " + Wheels + " wheels.");

}

}

class MotorCycle extends Vehicle //subclass of Vehicle

{

void showMotorCycleWheels()

{

System.out.println("Motor Cycle has " + Wheels + " wheels.");

}

}

class VehicleTest

{

public static void main(String args[])

{

Car myCar = new Car();

myCar.Wheels = 4;

myCar.showCarWheels();

MotorCycle myMoto = new MotorCycle();

myMoto.Wheels = 2;

myMoto.showMotorCycleWheels();

}

}

Post a Comment

Please do not enter any spam link in the comment box