Inheritance in JAVA: Public Class Parent
Inheritance in JAVA: Public Class Parent
Inheritance is a mechanism wherein a new class is derived from an existing class. In Java,
classes may inherit or acquire the properties and methods of other classes.
A class derived from another class is called a subclass, whereas the class from which a subclass is
derived is called a superclass. A subclass can have only one superclass, whereas a superclass may
have one or more subclasses.
Inheritance is the process wherein characteristics are inherited from ancestors. Similarly, in
Java, a subclass inherits the characteristics (properties and methods) of its superclass (ancestor).
For example, a vehicle is a superclass and a car is a subclass. The car (subclass) inherits all of
the vehicle’s properties. The inheritance mechanism is very useful in code reuse.
The keyword “extends” is used to derive a subclass from the superclass, as illustrated by the
following syntax:
Class Name_of_subclass extends Name_of superclass { //new fields and methods that
would define the subclass go here }
If you want to derive a subclass Rectangle from a superclass Shapes, you can do it as follows:
class Rectangle extends Shapes { …. }
Result:-
System.out.println();
animal.animalsleep();
animal.animaleat();
bird.birdsleep();
bird.birdeat();
dog.dogsleep();
dog.dogeat();
}
}
Result:-
An animal sleeps...
An animal eats...
A bird sleeps...
A bird eats...
A dog sleeps...
A dog eats...
Program 3: - Inheritance Simple Example
public class InheritanceParent
{
public String abc=null;
public String xyz=null;
Result:-