what is Inheritance ?
- In Java , It is to inherit attributes and methods from one class(super class) to another class(sub class).
- subclass(child/derived) - the class that inherits from another class.
- super-class (parent/base) - the class being inherited from
- To inherit from a class, use the extends keyword.
why to use ?
- It useful for code re-usability; reuse attributes(fields) and methods of an existing class when you create a new class.
- If you don not want other classes to inherit a class, use the final keyword.
Need of java inheritance:-
Code Re Usability:-
The code written super class you can not re write subclass it is common for all sub class ,child can directly use the parent properties(fields& properties)
Method overriding:-
method overriding : super class extends sub class ,the sub class inherit properties of parent class.
inheritance, this one of the way archive the run time polymorphism.
Abstraction
The concept of abstraction do not provide detail info in super class ,you need to implement your subclass,if you do not implement that subclass also Abstract class and you can not create object,so Abstraction achieve with inheritance.
how to inheritance work:-
- The extends keywords is used for inheritance in java. it enables the subclass inherit fields and methods(override) from the super class unless those properties private and also subclass add new methods.
- The extends keyword is used for establishes an " is-an relationship between child and parent class
Example:-
package oOps_Inheritance;
public class Calculation {
int z;
public void addition(int x ,int y)
{
z = x+y;
System.out.println("The sum of given number: "+z);
}
public void subtraction(int x, int y)
{
z= x-y;
System.out.println("The subtraction of given number: "+z);
}
}
package oOps_Inheritance;
public class My_Calculation extends Calculation{
public void multiplication(int x,int y)
{
z = x* y;
System.out.println("The sum of multiplication: "+z);
}
public static void main(String[] args) {
int a =20, b=10;
My_Calculation calculate = new My_Calculation();
calculate.addition(a, b);
calculate.subtraction(a, b);
calculate.multiplication(a, b);
}
}
Note:-
- subclass get everything from superclass(fields and methods) except constructors.if you used private members not accessed in subclass. From Superclass Protected fields and methods can access in the subclass(even other package)and same package.
- when you create an object of the subclass ,it also includes the members of superclass.
- you can use a super class reference to hold a subclass object , but it only access to super class members not a sub class members.Constructor not inherited/override , you can use the super() call the parent class constructor first line of the child constructor (when you create object in child first parent executed after to child constructor executed =>constructor chaining )and also you can call or access non-static fields and methods to call using super().
Parent p = new Child(); // Upcasting
p.superClassMethod(); // Allowed
p.childMethod(); // Not allowed directly
- If you want to access both superclass and subclass methods, use a subclass reference.
Child c = new Child();
c.superClassMethod(); //
c.childMethod(); //
But if you create a parent class reference and store a child class object , you can access only the parent class members, not child class members.
Example-2:-
package oOps_Inheritance;
public class Animal_SuperClass {
String name;
public void eat()
{
System.out.println("I can eat ");
}
//Note: protected methods and fields only accessible from the subclass of the class.
// why to use inherittance
/*
* code reusability
* Achive to(polymorphism & Abstraction)
* method overriding
*
*
*/
}
package oOps_Inheritance;
public class Lion extends Animal_SuperClass {
@Override
public void eat() {
super.eat();
System.out.println("I can eat non-veg");
}
public void infoDisplay()
{
System.err.println("My name is "+name);
}
public static void main(String[] args)
{
Lion lion = new Lion();
lion.name = "prasanth";
lion.eat();
lion.infoDisplay();
}
}
Types of Inheritance in java:-
- single Inheritance
single Inheritance , a single subclass extends from a single superclass.
Example:-
Example-2:-
- Multilevel Inheritance
The inheritance in which a base class inherited to a to derived class(subclass) and that derived class inherited to another derived class is known as multilevel inheritance.
Example:-
package oOps_Inheritance;
public class Animal_SuperClass {
String name;
public void eat()
{
System.out.println("I can eat ");
}
//Note: protected methods and fields only accessible from the subclass of the class.
// why to use inherittance
/*
* code reusability
* Achive to(polymorphism & Abstraction)
* method overriding
*
*
*/
}
// sub class
package oOps_Inheritance;
public class Lion extends Animal_SuperClass {
String position ;
String name = "Likera";
@Override
public void eat() {
super.eat();
System.out.println("I can eat non-veg");
}
public void infoDisplay()
{
System.err.println("My name is "+name+" .I am king of the jungle");
}
public static void main(String[] args)
{
Lion lion = new Lion();
lion.position="King";
lion.eat();
lion.infoDisplay();
}
}
// derived class extend another derived class.
package oOps_Inheritance;
public class Lion_Cub extends Lion {
String cubName;
@Override
public void infoDisplay()
{
super.infoDisplay();
cubName="simba";
System.err.println(cubName+" : My father name is "+name);
}
public static void main(String[] args) {
Lion_Cub cub = new Lion_Cub();
cub.position="Secound-King";
cub.infoDisplay();
}
}
Structure:-
grandpa(murgan.m)
|
V
son(Ravi.m)
|
V
child(RaviChild-prasanth.R)
- Hierarchical Inheritance:-
The hierarchical inheritance one base class(super class) extend multiple derived class(subclass) is known as hierarchical inheritance.
public class Murgan_SuperClass {
public static String name = "Murgan";
public void skillOne()
{
System.out.println("MySkill is Drawing well the picture");
}
public void skillTwo()
{
System.out.println("MySkill is Kig-Boxing chapion");
}
}
package oOps_Inheritance;
public class Ravi_SubClass extends Murgan_SuperClass{
public static void main(String[] args) {
Ravi_SubClass ravi = new Ravi_SubClass();
System.out.println("my fathe name is "+Murgan_SuperClass.name);
ravi.skillOne();
}
}
package oOps_Inheritance;
public class Kumar_SubClass extends Murgan_SuperClass{
public static void main(String[] args) {
Kumar_SubClass kumar = new Kumar_SubClass();
System.out.println("my fathe name is "+Murgan_SuperClass.name);
kumar.skillTwo();
}
}
Structure
Fateher(Murgan) ---------> Ravi(subclass)
| (extends)
| (extends)
V
Kumar(sublclass)
- Multiple Inheritance:-
- Multiple Inheritance is a one class have a more then one super class and inherit features from all parents classes.
- Java does not support the multiple inheritance only to achieve to the interface.
Example-syntax:-
interface Coder
{
//code
}
interface Tester
{
//code
}
class DevopsEngineer implements Tester,Coder
{
// override methods from interface
//programme logic
}
Structure:-
Ravi(father) Kanimozhi(mother)
| |
| (implements)|
v V
R.prasanth(son)
why not support multiple inheritance ?
Java does not support with multiple inheritance with class why? reason is to avoid Diamond/Ambiguity problem
Hybrid Inheritance in Java:-
Single Inheritance + Hierarchical Inheritance = Hybrid Inheritance;
Upcasting and Downcasting in Java
Parent p = new Child(); // Upcasting
p.superClassMethod(); // Allowed
p.childMethod(); // Not allowed directly
Parent p = new Child(); // Upcasting
Child c = (Child) p; // down casting
c.superClassMethod(); // Allowed
c.childMethod(); // allowed directly
// above only instance member only ,object is instance related.
Parent p = new Parent(); // p holds Parent object only
Child c = (Child) p; // Runtime Error: ClassCastException!
Reason : compiler allow because casting is ok , but run time jvm see that that object not a chile so
it thorws.
Exception in thread "main" java.lang.ClassCastException: Parent cannot be cast to Child
Resolution Time(which method/variable to use for compile or runtime)
Compile Time – Before running the program =>java compiler check method/variable decide which one to call.
Run Time -> JVM decides which method to execute based on the object. when the program running
Why Java resolve instance methods at runtime,
but variables (static & non-static) and static methods at compile time?
static type memory allocated once in memory , when at complile time/load time , who control ? JVM class loader.
instance type is new memory for each object at run time , who control it ? jvm during object creation.
1.Why are instance methods resolved at runtime?
when call instace method obj.run() java wait until the programm running ,to check or decide whic method to call because child can override parent method like who really created parent or child that all.
2.Why are variables (even non-static) resolved at compile-time?
when you use a variable obj.var1 which variable to use at compile time , based on the reference type,not a object , because methods only override not a variable.
3.Why are static methods and static variables resolved at compile-time?
static method/variable pointing to class not a object. loaded once when class loads.
(static method overriden)
what is class loader in java ?
A class loader is part of JRE ,that is responsible for loading .class files into memory when you programm runs. like you write java .java file compile to .class file JVM need it to run class loader it into memory
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.