0% found this document useful (0 votes)
18 views

Session 1.4 -1.6 Reference Association and Aggregation

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Session 1.4 -1.6 Reference Association and Aggregation

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

INHERITANCE

Inheritance

• Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object.
• Inheritance enables us to reuse methods and fields of the parent class.
• Moreover, you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
• Need for inheritance in java
• For Method Overriding (so runtime polymorphism can be
achieved).
• For Code Reusability.
PROS AND CONS OF INHERITANCE
Advantage of inheritance
• If we develop any application using concept of Inheritance
than that application have following advantages,
• Application development time is less.
• Application take less memory.
• Application execution time is less.
• Application performance is enhance (improved).
• Redundancy (repetition) of the code is reduced or
minimized so that we get consistence results and less
Note: In Inheritance the scope of access modifier increasing is allow
but storage cost.
decreasing is not allow. Suppose in parent class method access
modifier is default then it's present in child class with default or public
or protected access modifier but not private(it decreased scope).
Point of caution for inheritance in java:
• Privates members of parent class cannot be inherited into child class.
• The constructor of a parent class is never inherited into child class.
• One can achieve Inheritance regardless of package visibility.in other
words, a class with either default, public or protected visibility can be
extended.
• A class with default visibility can’t be extended outside its package.
• A class with public or protected visibility can be extended anywhere
outside its package.
Disadvantages:-
• One of the main disadvantages of inheritance is the increased time/effort it takes the program to
jump through all the levels of overloaded classes. If a given class has ten levels of abstraction
above it, then it will essentially take ten jumps to run through a function defined in each of
those classes
• Main disadvantage of using inheritance is that the two classes (base and inherited class) get
tightly coupled. This means one cannot be used independent of each other.
• Also with time, during maintenance adding new features both base as well as derived classes
are required to be changed. If a method signature is changed then we will be affected in both
cases (inheritance & composition)
• If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of
using that method.Here things can get a bit complicated in case of inheritance because our
programs will still compile, but the methods of the subclass will no longer be overriding
superclass methods. These methods will become independent methods in their own right.
RULES OF INHERITANCE
Features a subclass inherits from its
base class, through inheritance.
When a subclass inherits a base class, it inherits only the members of
superclass that are marked with public, protected visibility modes, these
members are -
Properties of the base class.
Functions of the base class.

Note - Base class members marked with private visibility mode are never
inherited.
Depending on the value of visibility-mode, multiple inheritance can be
performed in various ways -
• When a class inherits another class with the visibility-mode - public.
When a class is publicly inherited by another class, its public members become the
public members of the derived class, its protected members become the protected members of the
derived class, while the private members of any class cannot be inherite
• When a class inherits another class with the visibility-mode - private.
When a class is privately inherited by another class, its public members become the
private members of the derived class, its protected members become the private members of the
derived class, while the private members of any class cannot be inherited.
• When a class inherits another class with the visibility-mode - protected.
When a class is inherited by another class using the protected visibility mode, its public
members become the protected members of the derived class, its protected members become the
protected members of the derived class, while the private members of any class cannot be
inherited.The protected members cannot be directly accessed by the object of a class with a dot
operator, but can only be accessed from within the function of a class.
TYPES OF INHERITANCE IN JAVA
TYPES

OOPs support the FIVE different types of inheritance as


given below :
• Single inheritance
• Multi-level inheritance
• Multiple inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
In Class level Java does not support Multiple Inheritance. But
it can be implemented using interfaces
SINGLE INHERITANCE

Single inheritance is easy to understand.


When a class extends another one class
only then we call it a single inheritance.
The flow diagram shows that class B
extends only one class which is A. Here
A is a parent class of B and B would be a
child class of A.
SYNTAX
//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}

//Derived Class
class B extends A
{
public void fooB()
{
//TO DO:
}
}
Example 1
Class A public static void main(String args[])
{ {
public void methodA() B obj = new B();
{
obj.methodA(); //calling super class
System.out.println("Base class method");
method
}
obj.methodB(); //calling local method
}
}
Class B extends A }
{
public void methodB()
{
System.out.println("Child class method");
}
Example 2 of Single Inheritance
Below code represents Single Inheritance in Java, where we can see the Rectangle
class is inheriting only one parent class(Shape class).
public class Shape public static void main(String args[])
{
{
Rectangle r = new Rectangle();
int length; //Assigning values to Shape class
int breadth; attributes
} r.length = 10;
r.breadth = 20;
public class Rectangle extends
//Calculate the area
Shape r.calcualteArea();
{ System.out.println("The Area of
int area; rectangle of length \""
+r.length+"\" and
public void calcualteArea() breadth \""+r.breadth+"\"
{ is \""+r.area+"\"");
area = length*breadth; } O/P:The Area of rectangle of length
} "10" and breadth "20" is "200"
}
Example 3
class Faculty
{
float salary=30000;
} O/P:
class Science extends Faculty Salary is: 30000.0
{ Bonous is: 2000.0
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}
MULTIPLE INHERITANCE
“Multiple Inheritance” refers to the
concept of one class extending (Or
inherits) more than one base class.
The inheritance we learnt earlier had
the concept of one base class or
parent. The problem with “multiple
inheritance” is that the derived class
will have to manage the dependency
on two base classes.
POINTS TO REMEMBER

Note 1: Multiple Inheritance is very rarely used in software projects. Using


Multiple inheritance often leads to problems in the hierarchy. This results in
unwanted complexity when further extending the class.

Note 2: Most of the new OO languages like Small Talk, Java, C# do not
support Multiple inheritance. Multiple Inheritance is supported in C++.
Why Java doesn’t support Multiple
Inheritance?
// First Parent class / Error : Test is inheriting from multiple
class Parent1 // classes
{ class Test extends Parent1, Parent2
void fun()
{
{
System.out.println("Parent1");
public static void main(String args[])
} {
} Test t = new Test();
t.fun();
// Second Parent Class }
class Parent2 }
{
void fun() O/P:
{ Compile time error
System.out.println("Parent2");
}
} From the code, we see that, on calling the method fun() using
Test object will cause complications such as whether to call
Parent1’s fun() or Parent2’s fun() method.
Problems
1.The Diamond Problem:
On calling the method
fun() using Test object will cause
complications such as whether
to call Parent1’s fun() or Child’s
fun() method.
Therefore, in order to
avoid such complications Java
does not support multiple
inheritance of classes.
2. Simplicity

Multiple inheritance is not supported by Java using


classes , handling the complexity that causes due to multiple
inheritance is very complex. It creates problem during
various operations like casting, constructor chaining etc and
the above all reason is that there are very few scenarios on
which we actually need multiple inheritance, so better to
omit it for keeping the things simple and straightforward.
MULTILEVEL INHERITANCE
Multilevel inheritance refers to a
mechanism in OO technology where
one can inherit from a derived class,
thereby making this derived class the
base class for the new class. As you
can see in below flow diagram C is
subclass or child class of B and B is a
child class of A
SYNTAX
• Suppose, we have a form as shown above (class A is
class A the parent of class B and class B is the parent of class
{ C), then features of A are available for B, and features
of B (including that of A) are available for C. So, class
C get features of both A and B.
}
class B extends A
• In this case, class B is the parent to C and child to A.
{ such classes are generally known as intermediate
classes. When an object of class C is created,
} constructors of all the three classes will be executed.
class C extends B
• Even though the control goes to the constructor of C
{
first, the actual sequence of execution will be the
constructor of A first, the constructor of B next and
} constructor of C at last.
Example
Class X Class Z extends Y
{ {
public void methodX() public void methodZ()
{
{
System.out.println("class Z method");
System.out.println("Class X method");
}
} public static void main(String args[])
} {
Class Y extends X Z obj = new Z();
{ obj.methodX(); //calling grand parent class
public void methodY() method
{ obj.methodY(); //calling parent class
method
System.out.println("class Y method");
obj.methodZ(); //calling local method
} }
} }
HIERARCHICAL INHERITANCE
Inheritance is when an object or
class is based on another object
or class, using the same
implementation specifying
implementation to maintain the
same behavior. It is a mechanism
for code reuse and to allow
independent extensions of the
original software via public
classes and interfaces. The
relationships of objects or classes
through inheritance give rise to a
hierarchy. In hierarchical
inheritance a single class serves
as a superclass (base class) for
more than one sub class.
SYNTAX
Class A{ Class MainClass{
public void methodA(){ public void methodB(){
//Do Something //Do Something
} }
} public static void main(String
Class B extends A{ args[]){
public void methodB(){ B obj1 = new B();
C obj2 = new C();
//Do Something
obj1.methodA();
}
obj2.methodA();
}
}
Class C extends A{
}
public void methodC(){
//Do Something
}
}
Example //MainClass.java
class HierarchicalInheritance { class HierarchicalInheritanceMain {
void DisplayA() { public static void main(String
args[]) {
System.out.println("This
is a content of parent class");
System.out.println("Calling for child class C");
}
B b = new B();
}
b.DisplayA();
//B.java
b.DisplayC();
class A extends HierarchicalInheritance {
void DisplayB() {
System.out.println("Calling for child class B");
System.out.println("This A a = new A();
is a content of child class 1");
a.DisplayA();
}
a.DisplayB();
}
}
//c.java
}
class B extends HierarchicalInheritance {
void DisplayC() {
System.out.println("This
is a content of child class 2");
}
}
O/P:
Calling for child class C
This is a content of parent class
This is a content of child class 2
Calling for child class B
This is a content of parent class
This is a content of child class 1
HYBRID INHERITANCE
A hybrid inheritance is a combination
of more than one types of
inheritance. For example when class
A and B extends class C & another
class D extends class A then this is a
hybrid inheritance, because it is a
combination of single and
hierarchical inheritance. Let me show
you this diagrammatically:
class C class D extends A
{ {
public void disp() public void disp()
System.out.println("C"); {
} System.out.println("D");
class A extends C }
{ public static void
public void disp() main(String args[]){
System.out.println("A");
} D obj = new D();
class B extends C obj.disp();
{ }
public void disp() }
O/P:
System.out.println("B"); D
}
ASSOCIATION IN JAVA
ASSOCIATION
• The association relationship indicates that a class knows about, and holds a reference to,
another class. Associations can be described as a "has-a" relationship because the typical
implementation in Java is through the use of an instance field. The relationship can be bi-
directional with each class holding a reference to the other. Aggregation and composition are
types of association relationships.

• Associations join one or more of one thing against one or more of another thing. A professor
might be associated with a college course (a one-to-one relationship) but also with each
student in her class (a one-to-many relationship). The students in one section might be
associated with the students in another section of the same course (a many-to-many
relationship) while all the sections of the course relate to a single course (a many-to-one
relationship).
class CarClass{ class TransportCompany{
String carName; public static void main(String args[])
int carId; {
CarClass(String name, int id) Driver obj = new
{ Driver("Andy", "Ford", 9988);
this.carName = name;
this.carId = id; System.out.println(obj.driverName+" is a
} driver of car Id: "+obj.carId);
} }
class Driver extends CarClass{ }
String driverName;
Driver(String name, String cname, int
cid){
O/P:
super(cname, cid); Andy is a driver of car Id:
this.driverName=name; 9988Andy is a driver of car Id:
} 9988
}
Points to remember

• The association relationship indicates that a class knows


about another class. It can be described as a “has-a”
relationship between classes. The relationship between the
classes can be bi-directional.
• The association in Java follows a many-to-many
relationship.
• It joins two entirely separate entities.
package com.dataflair.association; public String getStudentName()
class Teacher {
{ return this.name;
private String name; }
Teacher(String name) }
{ class AssociationDemo
this.name = name; {
} public static void main (String[]
public String getTeacherName() args)
{ {
return this.name; Teacher teacherObj = new
} Teacher("Rahul Sir");
} Student studentObj = new
class Student Student("Renuka");
{
System.out.println(studentObj.getSt
private String name;
udentName() +
Student(String name) O/P:Renuka is "Student of
" is Student of +
{ Rahul Sir
teacherObj.getTeacherName());
this.name = name; }
}
Types of Association
in Java
There are two types
of association in Java
IS A RLATIONSHIP

• Is a Relationship is nothing but normal inheritance


• In order to make the parent class methods and members
directly available to the child class we use “extents”
keyword.
• The main advantage of using Inheritance is Code
Reusability
class P class Test
{
{
public static void main(String[]
public void m1() args)
{ {
System.out.println("Parent"); P p=new P();
} p.m1();
//Parent cannot access
} //p.m2(); child method
class C extends P C c=new C();
c.m2();
{ //Parent reference used
c.m1();
public void m2() to hold child object but
P p1=new C(); child methods cannot
{ p1.m1(); be called

System.out.println("Child"); //p1.m2();
} //C c1=new P();reference cannot
//Child
hold Parent object
} }
}
DEMO ON INHERITANCE

class Person{ }
class Employee extends Person{ }
class Teacher extends Person{ } true
class Maths_Teacher extends Teacher{ true
public static void main(String args[]){ true
Person p=new Person(); true
Employee e=new Employee();
Teacher t=new Teacher();
Maths_Teacher m=new Maths_Teacher();
System.out.println(e instanceof Person);
System.out.println(t instanceof Person);
System.out.println(m instanceof Person);
System.out.println(m instanceof Teacher);
}
}
AGGREGATION AND COMPOSITION
Aggregation – Has - A Relationship
• Aggregation is a special form of association. It is a relationship between two classes like
association, however its a directional association
• It is strictly a one way association.
• It represents a HAS-A relationship.
• In Aggregation, both the entries can survive individually which means editing one entity
will not effect the other entity

Aggregation Example in Java


• Consider two classes Student class and Address class. Every student has an address so the
relationship between student and address is a Has-A relationship.
• But if you consider its vice versa then it would not make any sense as an Address doesn’t need
to have a Student necessarily.
//Creating HAS-A relationship with Address
EXAMPLE 1 class
Address studentAddr;
StudentClass(int roll, String name, Address addr)
class Address {
{ this.rollNum=roll;
int streetNum; this.studentName=name;
String city; this.studentAddr = addr;
Address(int street, String c) }
{ public static void main(String args[]){
this.streetNum=street; Address ad = new Address(55, "Agra");
this.city =c; StudentClass obj = new StudentClass(123,
"Chaitanya", ad);
}
System.out.println(obj.rollNum+"
} "+obj.studentName);
public class StudentClass System.out.println("Address :
{ "+obj.studentAddr.streetNum+"
int rollNum; OUTPUT :
"+obj.studentAddr.city);

String studentName; } 123 Chaitanya


} Address : 55 Agra
class EmployeeExam{
EXAMPLE 2 int age;
Name n;
class Name{ public void display(int age,
String FirstName; Name n){
String MiddleName; System.out.println("Age:
String LastName; "+age); System.out.println("Full
Name: "+n.FirstName+"
public Name(String fname,
"+n.MiddleName+" "+n.LastName);
String mname,
}
String lname){
public static void main(String
FirstName=fname;
args[]){
MiddleName=mname;
EmployeeExam e=new
LastName=lname; EmployeeExam();
} Name n=new
} Name(“Subash",“Chandra",“Bose");
e.display(52,n);
Age: 52 }
Full Name: Subash Chandra }
Bose
Why we need Aggregation?

• To maintain code re-usability.


• Considering the previous Example : Suppose there are two other classes
College and Staff along with above two classes Student and Address.
• In order to maintain Student’s address, College Address and Staff’s address we
don’t need to use the same code again and again.
• We just have to use the reference of Address class while defining each of these
classes like:
– Student Has-A Address (Has-a relationship between student and
address)
– College Has-A Address (Has-a relationship between college and
address)
– Staff Has-A Address (Has-a relationship between staff and address)
Example Extended - Need for
Aggregation //Creating HAS-A relationship with Address class
class Address
{
int streetNum;
Address studentAddr;
String city; StudentClass(int roll, String name, Address addr){
Address(int street, String c) this.rollNum=roll; OUTPUT :
{
this.streetNum=street;
this.studentName=name; 123 Chaitanya
this.city =c; this.studentAddr = addr; Address : 55 Agra
} } College Name : VIT
} Address : 1 Vellore
class College
public static void main(String args[]){
{ Address ad = new Address(55, "Agra");
String collegeName; StudentClass obj = new StudentClass(123, "Chaitanya", ad);
//Creating HAS-A relationship with
Address class
Address col = new Address(1, "Vellore");
Address collegeAddr; College cl = new College("VIT",col);
College(String name, Address addr){ System.out.println(obj.rollNum+" "+obj.studentName);
this.collegeName = name;
this.collegeAddr = addr;
System.out.println("Address : "+obj.studentAddr.streetNum+"
} "+obj.studentAddr.city);
} System.out.println("College Name : "+cl.collegeName);
public class StudentClass
System.out.println("Address : "+cl.collegeAddr.streetNum+"
{
"+cl.collegeAddr.city);
int rollNum;
String studentName; }
}
Composition in Java

• Composition is a special case of aggregation.


• A restricted form aggregation is called composition.
• When an object contains the other object and the
contained object cannot exist without the other object,
then it is called composition.
• Both the entities are dependent on each other.
Example - Composition
class Honda extends Bike
class Bike
{
{
//inherits all properties of bike class
// declaring data members and methods
public void setStart()
private String color; {
private int wheels; HondaEngine e = new HondaEngine();
public void bikeFeatures() e.start();
{ }
System.out.println("Bike Color= "+color + " wheels= " + wheels); }
} class HondaEngine
{
public void setColor(String color)
public void start()
{
{
this.color = color;
System.out.println("Engine has been started.");
} }
public void setwheels(int wheels) public void stop()
{ {
this.wheels = wheels; System.out.println("Engine has been
stopped.");
}
}
}
}
Example – Composition Contd…
Program – Explanation
1. The above code contains three class - Class Bike, Class Honda, Class HondaEngine
2. Class Honda – Inherits Bike class and Has a Engine
3. Honda Class uses Honda Engine class, start() method via composition
4. Honda Engine (object) is used in Honda Bike (Class)

//Driver Class containing main method


class CompositionDemo OUTPUT :
{ Bike color= Black
public static void main(String[] args) wheels= 2
Engine has been started
{
Honda h = new Honda();
h.setColor("Black");
h.setwheels(2);
h.bikeFeatures();
h.setStart();
}
}
Importance of Composition:

• In composition we can control the visibility of other object


to client classes and reuse only what we need.
• Composition allows creation of back-end class when it is
needed
Comparing Composition and Inheritance:

• It is easier to change the class which is implementing composition than


inheritance.
• In inheritance, you cannot add method to a child class with the same method
name but a different return type as that method inherited from a parent class.
On the other hand, composition allows us to change the interface of a front-end
class without affecting back-end classes.
• Composition is done at run time i.e. dynamic binding while Inheritance is done at
compile time i.e. static binding.
• If you want to reuse code and there is no is-a relationship, then use composition.
You don’t need to use inheritance for code reuse.
• If you want polymorphism, but there is no is-a relationship, then use composition
with interfaces. You don’t need to use inheritance to get polymorphism.
Relationship in Java - Summary

We see the following relationships:


• Owners feed pets, pets please owners (association)
• A tail is a part of both dogs and cats
(aggregation / composition)
• A cat is a kind of pet (inheritance / generalization)
Relationship in Java - Summary
• To sum it up association is a very generic term used to represent when on class used the functionalities
provided by another class.
• We say it's a composition if one parent class object
owns another child class object and that child class
object cannot meaningfully exist without the parent
class object.
• If it can then it is called Aggregation.
Association vs Aggregation vs
Composition
• Although all three are related terms, there are some major differences in the way they relate
two classes. Association is a relationship between two separate classes and the association can
be of any type say one to one, one to may etc. It joins two entirely separate entities.

• Aggregation is a special form of association which is a unidirectional one way relationship


between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money
doesn’t need to have Wallet necessarily so its a one directional relationship. In this
relationship both the entries can survive if other one ends. In our example if Wallet class is not
present, it does not mean that the Money class cannot exist.

• Composition is a restricted form of Aggregation in which two entities (or you can say classes)
are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live
and a heart needs a Human body to survive. In other words when the classes (entities) are
dependent on each other and their life span are same (if one dies then another one too) then its
a composition. Heart class has no sense if Human class is not present.
MCQs
Mcqs

1.Which is true?
A "X extends Y" is correct if and only if X is a class and Y is an
interface
B. "X extends Y" is correct if and only if X is an interface and
Y is a class
C."X extends Y" is correct if X and Y are either both classes or
both interfaces
D. "X extends Y" is correct for all combinations of X and Y
being classes and/or interfaces
class Base{ public static void main(String[] args){
public Base(){ new Derived();
System.out.print("Base"); }
} }
} 2. Find the output of the code
public class Derived extends Base{ A. HELLODerived
public Derived(){
this("HELLO"); B. HELLOBaseDerived
System.out.print("Derived");
} C. BaseHELLODerived
public Derived(String s){
System.out.print(s); D. HELLODerivedBase
}
E. Compilation Error
public class Test{
class A{
public static void main(String[]
int b=10; args){
private A(){ A a = new B();
this.b=7; System.out.println(a.f());
} }
int f(){ }
return b; 3.Find the output of the code
} A. Compilation Fails
}
B. Prints 0
class B extends A{
int b; C. Prints 10
}
D. Prints 7

E. None of these
class Parent{
4.Determine the output of
public void method(){
the code
System.out.println("Hi i am
parent"); A. Compiles successfully and
} print
}
public class Child extends Parent{ B. Compiles successfully and
protected void method(){ print
System.out.println("Hi i am
Child"); C. Compile time error
}
public static void main(String
D. Run Time error
args[]){
Child child = new Child();
child.method(); E. None of This
}
}
5.What will be the output of public class Test{
the code public static void main(String
class A{ args[]){
int i = 10;
A a = new B();
public void printValue(){
a.printValue();
System.out.print("Value-
A"); }
} }
} A. Value-B
B. Value-B Value-A
class B extends A{ C. Value-A
int i = 12; D. Value-AValue-B
public void printValue(){
E. None of these
System.out.print("Value-
B");
}
}
6.The concept of multiple inheritance is implemented in Java
by
I. Extending two or more classes.
II. Extending one class and implementing one or more
interfaces.
III. Implementing two or more interfaces.
A. Only (II)

B. (I) and (II)

C. (II) and (III)

D. Only (I)

E. Only (III)
6. void test(){
class A{
7. // insert code here
A(String s){}
8. }
9. }
A(){}
7.Which of the below code can
} be insert at line 7 to make clean
compilation ?
1. class B extends A{ A. A a = new B();
2. B(){}
3. B(String s){ B. A a = new B(5);
4. super(s);
5. } C. A a = new A(String s);

D. All of the above

E. None of these
8. Determint the outpt
public class Test{
class Person{
public void talk(){ public static void main(String
System.out.print("I am a args[]){
Person"); Person p = new Student();
} p.talk();
} }
}
class Student extends Person{
A. I am a Person
public void talk(){
System.out.print("I am a
Student"); B. I am a Student
}
} C. I am a Person I am a Student

D. I am a Student I am a Person
public class Test{ 9. What will be the output
public static void printValue(int i, int
j, int k){ A. long
System.out.println("int"); B. int
} C. Compilation fails
D. Compilation clean but throws
public static void RuntimeException
printValue(byte...b){ E. None of these
System.out.println("long");
}

public static void main(String... args)


{
byte b = 9;
printValue(b,b,b);
}
}
10. What will be the output of the public class Test{
following code public static void main(String
class A{ args[]){
static void method(){ A a = new B();
a.method();
System.out.println("Class A method"); }
} }
}
A. Class A method
class B extends A{
static void method(){
B. Class B method

System.out.println("Class B method"); C. Compilation Error


}
} D. Runtime Error

E. None of these
Answers

1. C
2. C
3. A
4. C
5. A
6. C
7. A
8. B
9. B
10.A

You might also like