INHERITANCE
• Inheritance is a mechanism in which one class acquires the property of another class
•
The parent class is called a superclass and the inherited class is called a
subclass.
•
The keyword extends is used by the subclass to inherit the features of the superclass.
•
Inheritance is important since it leads to the reusability of code.
• Multiple
inheritance is not supported by Java
Java Inheritance Syntax:
class subClass extends superClass
{
//methods and fields
}
JAVA SUPPORTS:
1. SINGLE
INHERITANCE
2. HIERARCHICAL
INHERITANCE
3. MULTILEVEL
INHERITANCE
Example 01:
package Inheritance;
//Single Inheritance in Java
class Big //Base
{
public void house()
{
System.out.println("Have Own 2BHK House.");
}
}
class sec extends Big //Derived
{
public void car()
{
System.out.println("Have Own Audi Car.");
}
}
public class single {
public static void main(String args[])
{
sec o =new sec();
o.car();
o.house();
}
}
Example 02:
package Inheritance;
//Multilevel Inheritance in Java
class GrandFather {
public void house() {
System.out.println("3 BHK House.");
}
}
class father extends GrandFather{
public void land() {
System.out.println("5 Arcs of Land..");
}
}
class son extends father {
public void car() {
System.out.println("Own Audi Car..");
}
}
public class multilevel {
public static void main(String args[]) {
son o = new son();
o.car();
o.house();
o.land();
}
}
Example 03:
package Inheritance;
//Hierarchical Inheritance in Java
class shape {
float length, breadth, radius;
}
class rect extends shape {
public rect(float l, float b) {
length = l;
breadth = b;
}
float rectangle_area() {
return length * breadth;
}
}
class circle extends shape {
public circle(float r) {
radius = r;
}
float circle_area() {
return 3.14f * (radius * radius);
}
}
class square extends shape {
public square(float l) {
length = l;
}
float square_area() {
return (length * length);
}
}
public class Hierarchical {
public static void main(String[] args) {
rect o1 =new rect(2,5);
System.out.println("Area of Rectangle : "+o1.rectangle_area());
circle o2 =new circle(5);
System.out.println("Area of Circle : "+ o2.circle_area());
square o3 =new square(3);
System.out.println("Area of Square : "+o3.square_area());
}
}
0 Comments