Aggregation and Inheritance
Aggregation and Inheritance
Code Re-use
Aggregation
&
Inheritance
Object Oriented Programming
If the code you write Has-A instance of the class you re-use, then it's Aggregation
If the new code you write Is-A derivation of the code you re-use, then it's Inheritance.
Inheritance
Object Oriented Programming
When you re-use code written before by declaring a previously defined class in your
code, then you are using aggregation.
aggregation
e.display();
e2.display();
}
}
Object Oriented Programming
The idea behind inheritance in java is that you can create new classes that are built
upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent
class, and you can also add new methods and fields.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
properties == fields
Behavior == methods
Object Oriented Programming
Object Oriented Programming
SuperClass is the parent
SubClass is the child
Object Oriented Programming
h
Object Oriented Programming
The extends keyword indicates that you are making a new class that derives
from an existing class.
●
In the terminology of Java, a class that is inherited is called a super class.
●
The new class is called a subclass.
Object Oriented Programming
Understanding the simple example of inheritance
class Employee{
float salary=40000;
}
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java through class.
It's better to get a Compile time error than to get a runtime error in your program.
class A{
void msg(){System.out.println("Class A");}
}
class B{
void msg(){System.out.println("Class B");}
}