BY TEJAS
Inheritance is a very important concept in object-oriented programming. Inheritance is a very simple concept. All you have to do is read this article carefully and try to execute each of these programs.
Inheritance in Java
Simply put, if we look at what inheritance is, Before we start Inheritance, let's all assume that we know the concept of classes in Java. Because inheritance is the advanced concept of a class.
As you know, every java program must have one class, that class is known as the base
class. And in Java, we can create one or more classes.
If we create a class, we also create a lot of objects of that class. Now, if we create a new class,
we call it a derived class.
ADVERTISEMENT
Inheritance is the process of creating new classes from existing classes. The new classes we create are called derived classes and the existing classes are called base classes.
Suppose you create a new class, you want the same objects in the class as the base class objects in
the newly created derived class, as well as some new objects in that derived class. So the simple
thing is you definitely don't want to rewrite the same code over and over again.
So inheritance helps us in these things. Inheritance helps you to use the objects of one class in
another class. We can use all base class objects (functions) in a derived class without rewriting
the same code. To do that we need to use the keyword extends
.
ADVERTISEMENT
The following program will give you an idea of how to use inheritance.
class A {
void msgA(){
System.out.println("Welcome to Inheritance in Java");
}
}
class B extends A {
//suppose if it were
public static void main(String args[]){
B obj=new B();
obj.msgA(); //Now which msgA() method would be invoked
}
}
You must have seen the above program?
In it, we have created two classes, one called Class A and the other B.
In class A we have created the object msgA()
in which we print a line "Welcome to inheritance in
java
".
Now let's move on to Class B. In B class, we have taken all the objects of class A in class B
using the keyword extends
. And now we have started the main()
function in
class B in which we have
declared B as an object. And with the help of that object, we have called the object which in class
A as a msgA()
.
Below is an output of the above program.
Welcome to Inheritance in Java
ADVERTISEMENT
In this article, you have seen Java inheritance. Basically, inheritance is a process of creating new
classes from the existing classes. We also look at a program in this, so your conception has been
cleared.
If you like this article then comment and you can also comment even though there is a
doubt.