0

Please guys make me understand what exactly is inheritance and how to use it in a java program?

10th Dec 2016, 3:14 PM
Anand Chourasiya
Anand Chourasiya - avatar
3 Réponses
+ 2
1) inheritance allows a class to inherit(use as its own) the members of other class using the keyword extends 2)class B inherits class A ; it means B is the subclass of A & A is the super class of B 3)A subclass can have only one superclass A superclass can have more than one subclass example: consider the following java code class A { int a,b; void display() { System.out.println(a+" "+b); } } class B { int a,b; void display() { System.out.println(a+" "+b); } } class Main { public static void main(String args[]) { A var1=new A(); B var2=new B(); var1.a=10; var1.b=20; var2.a=30; var2.b=40; var1.display(); var2.display(); } } you will notice that the variables and function in both the class are exactly the same. So in order to reduce the effort of writing the same code again and again we use the concept of inheritance. Using the concept of inheritance, the above segment of code can be written as class A { int a,b; void display() { System.out.println(a+" "+b); } } class B extends class A { } class Main { public static void main(String args[]) { A var1=new A(); B var2=new B(); var1.a=10; var1.b=20; var2.a=30; var2.b=40; var1.display(); var2.display(); } }
10th Dec 2016, 3:44 PM
Rishi Anand
Rishi Anand - avatar
+ 1
think of it as a frame you made now its easy for you to get the shape. main class() you can call functions from it in child classes
10th Dec 2016, 3:31 PM
Sun
Sun - avatar
- 1
it basically means, if u hv written some code that is used many times, then just write it once in base class and use it in derived class that need it, it can be best understood through simple examples check out course example s and work them through.
10th Dec 2016, 3:25 PM
Morpheus
Morpheus - avatar