(What is subclass and superclass)
It is possible to inherit attributes and methods from one class to another .
we group the inheritance in to two categories.
Subclass(Child) :-
the class that inherits from another class.
Superclass(Parent) :-
the class being inherited from . To inherit from a class, use the extends keyword .
In the example below , the Car class (subClass) inherits the attributes and methods from the vehicle class(superclass)
Inheritance in java is a mechanism in which one object acquires all the properties and behaviours of a parent object. It is an important part of OOPS.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. Moreover you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as parent child relationship.
Why we use Inheritance in Java :-
For method overriding
for code resuability
Term used in Inheritance
Class :- A class is a group of objects which has common properties. it is a template or blueprint from which objects are created.
Subclass/Child class :- Subclass is a class which inherits the other class. it is also called a derived class, extended class, or child class.
Superclass/ Parent Class:- Superclass is the class from where a subclass inherits the features . It is also called a base class or a parent class.
Reusability :- As the name specifies , reusability is a mechanism which facilitate you to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
public class Vehicle {
Protected String brand ="Ford";
public void honk(){
System.out.println("Tut");
}
}
class Car extends Vehicle{
private String modelName ="mustang";
public static void main(String [] args){
Car myCar = new Car();
myCar.honk();
}
}