6. Inheritance

6. Inheritance


  • While developing an application the business classes and functional classes are represented in a diagram known as class diagram
  • The class diagram provides following three information

  1. Name of the classes
  2. The data members or fields of the classes
  3. Constructors and behaviors (Methods) of the class

What is Association in Java?

  • ?The association establishes a relationship between two?classes?through their?objects. The relationship can be one-to-one, one-to-many, many-to-one, and many-to-many.

Example Program:

class CarClass
{
	String carName;
	double carSpeed;
	int carId;
	
	CarClass(String name, double speed, int Id)
	{
		this.carName=name;
		this.carSpeed=speed;
		this.carId=Id;
	}
}
class Driver
{
	String driverName;
	int driverAge;
	
	Driver(String name, int age)
	{
		this.driverName=name;
	    this.driverAge=age;
	}
}
class TransportCompany
{
	public static void main(String args[])
	{
		System.out.println("Program starts...");
		CarClass obj= new CarClass("Ford", 180.15, 9988);
		Driver obj2 = new Driver("Pramod", 26);
		System.out.println(obj2.driverName+" is a driver of car Id: "+obj.carId);
		System.out.println("Car Name    : "+obj.carName);
		System.out.println("Speed of Car: "+obj.carSpeed);
		System.out.println("Driver Age  : "+obj2.driverAge);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Pramod is a driver of car Id: 9988

Car Name? ? : Ford

Speed of Car: 180.15

Driver Age? : 26

Program ends...

  • In the above example, there is a one to one relationship (Association) between two classes:?Car?and?Driver. Both the classes represents two separate entities.

Aggregation in Java (Has-A)

  • Aggregation is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship. It is a more specialized version of the?association relationship. The aggregate class contains a reference to another class and is said to have ownership of that class. Each class referenced is considered to be?part-of?the aggregate class
  • If a class has an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.?
  • Consider a situation; Employee object contains many information’s such as id, name, email Id etc. It contains one more object named address, which contains its own information’s such as city, state, country, zip code etc. as given below.?

Note:?

  • Ownership occurs because there can be no cyclic references in an aggregation relationship.
  • If Class A contains a reference to Class B and Class B contains a reference to Class A then no clear ownership can be determined and the relationship is simply one of association.

class Employee
{  
	int id;  
	String name;  
	Address address; //Address is a class 
}        

In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.?

Why use Aggregation?

  • For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

class Operation
{  
    int square(int n)
    {  
    	return n*n;  
    }  
}
class Circle
{  
    Operation op;//aggregation or Has-A relationship 
    double pi=3.14;  
    
    double area(int radius)
    {  
      op=new Operation();  
      int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  
      return pi*rsquare;  
    }        
       
    public static void main(String args[])
    { 
    	System.out.println("Program starts...");
    	Circle c=new Circle();  
    	double result=c.area(5);  
    	System.out.println("Result: "+result); 
    	System.out.println("Program ends...");
    } 
}          

Output:

Program starts...

Result: 78.5

Program ends...

When use Aggregation?

  • Code reuse is also best achieved by aggregation when there is no is-a relationship.
  • Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation

  • In this example, Employee has an object of Address; address object contains its own information’s such as city, state, country etc. In such case relationship is Employee HAS-A address.?
  • Aggregation is a special form of?association. It is also a relationship between two classes like association, however it’s a?directional?association, which means it is strictly a?one way association.?It represents a?Has-A?relationship.
  • For example consider two classes Student class and Address class. Each student must have an address so the relationship between student and address is a Has-A relationship. But if you consider it’s vice versa?then it would not make sense as an?Address?doesn’t need to have a?Student necessarily. Below example shows this?theoretical?explanation in a sample java program. Student Has-A Address

class Address
{
   int streetNum;
   String city;
   String state;
   String country;
   Address(int street, String c, String st, String coun)
   {
       this.streetNum = street;
       this.city = c;
       this.state = st;
       this.country = coun;
   }
}
class StudentClass
{
   int rollNum;
   String studentName;
   Address studentAddr; 
   
   StudentClass(int roll, String name, Address addr)
   {
       this.rollNum=roll;
       this.studentName=name;
       this.studentAddr = addr;
   }
   public static void main(String args[])
   {
	 System.out.println("Student Details: ");
       Address ad = new Address(55, "Mandya", "Karnataka", "India");
       StudentClass obj = new StudentClass(123, "Pramod", ad);
       System.out.println("Student Roll Number: "+obj.rollNum);
       System.out.println("Student Name       : "+obj.studentName);
       System.out.println("Sreet Name         : "+obj.studentAddr.streetNum);
       System.out.println("City Name          : "+obj.studentAddr.city);
       System.out.println("State              : "+obj.studentAddr.state);
       System.out.println("Country            : "+obj.studentAddr.country);
    }
}        

Output:

Student Details:?

Student Roll Number: 123

Student Name ? ? ? : Pramod

Sreet Name ? ? ? ? : 55

City Name? ? ? ? ? : Mandya

State? ? ? ? ? ? ? : Karnataka

Country? ? ? ? ? ? : India

  • The above example shows the?Aggregation?between Student and Address classes. You can see that in Student class I have used Address class to obtain student address. It’s a?typical?example of?Aggregation?in Java.

Why we need Aggregation?

To maintain code re-usability. To understand this lets consider the above example again. 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)

Hence we can improve code re-usability by using Aggregation relationship.

Composition

  • Composition?is the design technique to implement?has-a?relationship in classes.
  • Java composition is achieved by using instance variables that refers to other objects. For example, a?Person has a?Job.

?What is Composition in java?

  • Composition is restricted form of Aggregation. For example a class?Car?cannot exist without?Engine.

class Car
{
	 private Engine engine;
 	Car(Engine en)
 	{
  		engine = en;
 	}
}        

Association vs Aggregation vs Composition

Let’s discuss?difference between Association, Aggregation and 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 which 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 it’s 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 it’s a composition. Heart class has no sense if Human class is not present.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example:?A Student and a Faculty are having an association.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.


Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example:?A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.

Example:?A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Note:?

  • Aggregation : Facebook?has a?user
  • Composition: Each user in Facebook?has a?session.
  • Association : People?uses a?browser

Inheritance

  • Inheriting member of one class to another class in known as inheritance
  • Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object
  • The class from where members are inherited is known as super class or parent class
  • The class to which members are inherited is known as sub class or child class
  • The class can inherits from any other class by using a keyword “Extends”
  • The general syntax is

  • 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 parent class, and you can add new methods and fields also.
  • Inheritance represents the?IS-A relationship, also known as?parent-child?relationship.
  • The?extends keyword?indicates that you are making a new class that derives from an existing class.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Understanding the simple example of inheritance

  • As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is?Programmer IS-A Employee. It means that Programmer is a type of Employee.

class Employee
{
	float salary=40000;  
}  
public class Programmer extends Employee
{
	int bonus=10000;  
	public static void main(String args[])
	{
		System.out.println("Program starts...");
		Programmer p=new Programmer();  
		System.out.println("Programmer salary is:"+p.salary);  
		System.out.println("Bonus of Programmer is:"+p.bonus); 
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Programmer salary is:40000.0

Bonus of Programmer is:10000

Program ends...


  • In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

Types of inheritance?

  • If a class inherits from one class super class than it is known as Single Inheritance

  • If a class inherits from one super class, the super class is again inheriting from another class is known as Multilevel Inheritance

  • A class inheriting from more than one super class is known as Multiple Inheritance, java doesn’t support multiple inheritance using classes

  • One super class can be inherited to more than one sub classes, this is known as Hybrid Inheritance?

  • When the sub class inherits the class only the non-static members of super class will be inherited to the sub class
  • Static members of super class will not be inherited to the sub class instance

Note:?

  • if a class inherits members from another class then that class is a owner of inherited member hence it can modify the inherited members but we can’t modify the static members so static members are not inherited to the subclass
  • only non-static members are inherited to the sub classes?

//Single inheritance
class A
{
	// super or base or parent class
	int i = 10;
}
class B extends A
{
	//sub or derived or child class
	double d = 12.24;
}
public class Demo 
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		A a = new A();
		B b = new B();
		System.out.println("i= "+a.i);
		System.out.println("---------------");
		System.out.println("i= "+b.i);
		System.out.println("d= "+b.d);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

i= 10

---------------

i= 10

d= 12.24

Program ends...

//Multi-level inheritance
class A
{
	// super or base or parent class
	int i = 10;
}
class B extends A
{
	//sub or derived or child class
	double d = 12.24;
}
class C extends B
{
	//sub or derived or child class
	String s = "Java";
}
public class MultilevelInheritance 
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		A a = new A();
		B b = new B();
		C c = new C();
		System.out.println("i= "+a.i);
		System.out.println("---------------");
		System.out.println("i= "+b.i);
		System.out.println("d= "+b.d);
		System.out.println("---------------");
		System.out.println("i= "+c.i);
		System.out.println("d= "+c.d);
		System.out.println("s= "+c.s);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

i= 10

---------------

i= 10

d= 12.24

---------------

i= 10

d= 12.24

s= Java

Program ends...

//Hybrid inheritance
class A
{
	int i = 10;
}
class B extends A
{
	double d = 12.24;
}
class C extends A
{
	String s = "Java";
}
public class HybridInheritance 
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		A a = new A();
		B b = new B();
		C c = new C();
		System.out.println("i= "+a.i);
		System.out.println("---------------");
		System.out.println("i= "+b.i);
		System.out.println("d= "+b.d);
		System.out.println("---------------");
		System.out.println("i= "+c.i);
		System.out.println("s= "+c.s);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

i= 10

---------------

i= 10

d= 12.24

---------------

i= 10

s= Java

Program ends...

Data Overriding

  • Declaring a variable in sub class with same name as super class and initializing different value is known as data overriding
  • Whenever we perform data overriding inside subclass object we get the overridden values
  • ?A sub class can refer a super class member by using a special keyword “Super”
  • “Super” keyword must be used inside subclass constructor body or subclass non-static context

Super keyword

  • The super keyword in java is a reference variable that is used to refer immediate parent class object.
  • Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of java super Keyword

  1. Super is used to refer immediate parent class instance variable.
  2. Super () is used to invoke immediate parent class constructor.
  3. Super is used to invoke immediate parent class method.

class A
{
	int i = 10;
}
class B extends A
{
	// data overriding 
	int i =12;
	void test1()
	{
		System.out.println("Sub class i= "+this.i);
		System.out.println("Super class i= "+super.i);
	}
}
public class DataOverriding
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		B b = new B();
		b.test1();
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Sub class i= 12

Super class i= 10

Program ends...

  • The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:

class Person
{  
	void message()
	{
		System.out.println("welcome");
	}  
}    
class SuperKeyword extends Person
{  
	void message()
	{
		System.out.println("welcome to java");
	}
	void display()
	{  
		message();//will invoke current class message() method  
		super.message();//will invoke parent class message() method  
	}
	public static void main(String args[])
	{  
		System.out.println("Program starts...");
		SuperKeyword s=new SuperKeyword();  
		s.display();		
		System.out.println("Program ends...");
	}  
}          

Output:

Program starts...

welcome to java

welcome

Program ends...

  • In the above example Student and Person both classes have message () method if we call message () method from Student class, it will call the message () method of Student class not of Person class because priority is given to local.?

  • In case there is no method in subclass as parent, there is no need to use super. In the example given below message () method is invoked from Student class but Student class does not have message () method, so you can directly call message () method.?

Super () Calling Statements/ Call to Super () Statements

class P
{
	P()
	{
		super();
		System.out.println("Running P() constructor");
	}	
}
class Q extends P
{
	Q()
	{
		super();
		System.out.println("Running Q() constructor");
	}	
}
class R extends Q
{
	R()
	{
		super();
		System.out.println("Running R() constructor");
	}	
}
public class Demo 
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		R r = new R();
		System.out.println("Program ends...");
	}

}        

Output:

Program starts...

Running P() constructor

Running Q() constructor

Running R() constructor

Program ends...

class P
{
	P()
	{
		super();
		System.out.println("Running P() constructor");
	}	
}
class Q extends P
{
	//compiler write default constructor
	//inside default constructor 'Super()' will be written by constructor
}
class R extends Q
{
	R()
	{
		super();
		System.out.println("Running R() constructor");
	}	
}
public class Demo 
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		R r = new R();
		System.out.println("Program ends...");
	}

}        

Output:

Program starts...

Running P() constructor

Running R() constructor

Program ends...

class P
{
	P()
	{
		super();
		System.out.println("Running P() constructor");
	}	
}
class Q extends P
{
	Q(int a)
	{
		System.out.println("Running Q(int) constructor");
	}
	Q(double b)
	{
		System.out.println("Running Q(double) constructor");
	}
	Q(int a, double b)
	{
		System.out.println("Running Q(int, double) constructor");
	}
}
class R extends Q
{
	R()
	{
		super(12);
		System.out.println("Running R() constructor");
	}	
}
public class SuperConstrucotr 
{
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		R r = new R();
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Running P() constructor

Running Q(int) constructor

Running R() constructor

Program ends...

//Multiple inheritance
class A
{
	int i = 10;
}
class B 
{
	double d = 12.24;
}
class C extends A, B
{
	// class can't inherit from more than one super class
	String s = "Java";
}        

  • If we try to do multiple inheritance it leads to “diamond problem”
  • Whenever a sub class instance is created, the subclass constructor calls the super class constructor by using super () statements
  • The super class constructor will again call its super class constructor by using super() statements, this is known as constructor chain
  • In every constructor body compiler writes super () statement by default
  • The super () statements written by compiler always call the default constructor of super class
  • If the super class doesn’t have default constructor then the subclass constructor should call explicitly the argument constructor of super class
  • The super() statement must be first statement of constructor?
  • We cannot develop two super statement inside the one constructor body
  • Also super () and this () statement cannot be developed inside the constructor body
  • Every java class must inherit from object class, object class is a super most class for all java classes
  • A class cannot inherit from more than one super class because in sub class constructor we cannot develop two super statements and also the object class cannot be inherited its one class in more than one path, this leads to “Diamond Problem”??

Note:?

  1. Every instance in java should consist of object class members
  2. In object class only default constructor exists
  3. Constructor of a super class cannot be inherited to sub class?

Constants

  • In java we use a keyword “final” for declaring the constant variable.
  • The final keyword in java is used to restrict the user. The java final keyword can be used in many contexts.
  • ?Final can be:

  1. Variable
  2. Method
  3. Class

  • The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.?

?Java final variable

  • If you make any variable as final, you cannot change the value of final variable (It will be constant).

Example of final variable

There is a final variable speed limit, we are going to change the value of this variable, but it can't be changed because final variable once assigned a value can never be changed.?

class Bike
{  
	 final int speedlimit=90;//final variable  
	 void run()
	 {  
	  speedlimit=400;  
	 }  
	 public static void main(String args[])
	 {  
		 Bike obj=new  Bike();  
		 obj.run();  
	 }  
}        

Output: Compile Time Error

  • In the above program we declared the final variable “speedlimit” as final and we are trying to assign different value inside the method run(), but it’s not possible, coz once we declare any variable as final, we can’t change the value. It is constant. Even if we try to assign new value we will get compile time exception “The final field Bike.speedlimit cannot be assigned”.

Java final method

  • If you make any method as final, you cannot override it.

class Bike
{  
	  final void run()
	  {
		  System.out.println("running");
	  }  
}  
class Honda extends Bike
{
	void run()
	{
		System.out.println("running safely with 100kmph");
	}
	public static void main(String args[])
	{  
	   Honda honda= new Honda();  
	   honda.run();  
	}  
}        

Output: Compile time error

  • In the above program we developed two classes, in bike class we created the final method run () and developed one more run method in the class Honda and we are inheriting the bike class to Honda class and overriding the final run method.
  • ?If in the above program, we get compile time error. Coz we can inherit the final method but we can’t override the final methods.
  • Output will be “Cannot override the final method’

Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:?

class Bike
{
	final void run()
	{
		System.out.println("running...");
	}  
}  
public class Honda2 extends Bike
{
	public static void main(String args[])
	{
		System.out.println("Program starts...");
		new Honda2().run();
		System.out.println("Program ends...");
	}
}         

Output:

Program starts...

running...

Program ends...

Java final class

  • If you make any class as final, you cannot extend it.

Output: Compile time error

  • In the above program we have developed two classes, made business class as a final class and one functional class.
  • Here, we are trying to extend the final class but we will get a compile time error saying “The type Honda cannot subclass the final class Bike1”
  • Cos, final class cannot be inherited.

What is blank or uninitialized final variable?

  • A final variable that is not initialized at the time of declaration is known as blank final variable.
  • If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.?
  • It can be initialized only in constructor.

class Student
{  
	int id;  
	String name;  
	final String PAN_CARD_NUMBER;  
}        

Output: Compile time error “The blank final field PAN_CARD_NUMBER may not have been initialized”

Can we initialize blank final variable?

Yes, but only in constructor. For example:

class Bike6
{  
    final int speedlimit;//blank final variable  
      
    Bike6()
    {  
    	speedlimit=70; // intializing final variable in constructor 
    	System.out.println(speedlimit);  
    }      
    public static void main(String args[])
    {  
    	System.out.println("Program starts...");
    	new Bike6();  
    	System.out.println("Program ends...");
    }  
}        

Output:

Program starts...

70

Program ends...

Static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

class A
{
	static final int data;//static blank final variable  
	static{ data=50;}  
	public static void main(String args[])
	{ 
		System.out.println("Program starts...");
	    System.out.println(A.data);  
	    System.out.println("Program ends...");
	}  
}        

Output:

Program starts...

50

Program ends...

What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

class B
{
	int cube(final int n)
	{  
	   n=n+2;//can't be changed as n is final  
	   n*n*n;  
	}  
	public static void main(String args[])
	{
		System.out.println("Program starts...");
	    B b=new B();  
	    b.cube(5);  
	    System.out.println("Program ends...");
	 } 
}        

Output: “Compile time error”

Can we declare a constructor final?

No, because constructor is never inherited.

要查看或添加评论,请登录

Srinivas Prasad K T的更多文章

社区洞察

其他会员也浏览了