Sunday, October 28, 2018

What is inheritance in Java?

One of the fundamental concepts of Java is inheritance. Inheritance is everywhere in Java. It's safe to say that it's almost (almost?) impossible to write even the tiniest Java program without using inheritance.

It makes sense to inherit from an existing class Vehicle to define a class Car, since a car is a vehicle. Car will have a basic behavior and all child classes will extend this basic behavior from the parent class i.e Car without having a need to implement them.

IS-A


In OO, the concept of IS-A is based on class inheritance or interface implementation. IS-A is a way of saying, "this thing is a type of that thing." For example, a Mustang is a type of horse, so in OO terms we can say, "Mustang IS-A Horse." Honda IS-A Car. Tomato IS-A Vegetable

A basic example of inheritance.


class One {
public One() {
   System.out.println("one");
}
}
class Two extends One {
public Two() {
   System.out.println("two");
}
}
class Demo
{
public static void main(String args[]) {
   Two t = new Two();
}

Output:
one
two


No comments:

Post a Comment