- The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance.
- The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class.
Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.
Parent Class:
- The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class.
- Inheritance is a process of defining a new class based on an existing class by extending its common data members and methods.
- Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not be rewritten in the child class.
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent class. The class XYZ is inheriting the properties and methods of ABC class.
class XYZ extends ABC
{
}
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class. For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends the same class. For example, classes B, C & D extends the same class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a child class has two parent classes. For example class C extends both classes A and B. Java doesn’t support multiple inheritance, read more about it here.
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example class A & B extends class C and another class D extends class A then this is a hybrid inheritance example because it is a combination of single and hierarchical inheritance.
Inheritance and Method Overriding
When we declare the same method in child class which is already present in the parent class the this is called method overriding. In this case when we call the method from child class object, the child class version of the method is called. However we can call the parent class method using super keyword as I have shown in the example below:
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
void disp(){
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
System.out.println("Constructor of Child");
}
void disp(){
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[]){
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The output is :
Constructor of Parent
Constructor of Child
Child Method
Parent Method
What is Association in java?
Association establishes relationship between two separate classes through their objects. The relationship can be one to one, One to many, many to one and many to many.
Association Example
class CarClass{
String carName;
int carId;
CarClass(String name, int id)
{
this.carName = name;
this.carId = id;
}
}
class Driver extends CarClass{
String driverName;
Driver(String name, String cname, int cid){
super(cname, cid);
this.driverName=name;
}
}
class TransportCompany{
public static void main(String args[])
{
Driver obj = new Driver("Andy", "Ford", 9988);
System.out.println(obj.driverName+" is a driver of car Id: "+obj.carId);
}
}
In the above example, there is a one to one relationship(Association) between two classes: CarClass and Driver. Both the classes represent two separate entities.
Association is relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many.
In Object-Oriented programming, an Object communicates to other Object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.
Aggregation
Aggregation is a special form of association. It is a relationship between two classes like association, however its 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. 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. Lets write this example in a java program.
Student Has-A Address
It is a special form of Association where:
- It represents Has-A relationship.
- It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice versa is not possible and thus unidirectional in nature.
- In Aggregation, both the entries can survive individually which means ending one entity will not effect the other entity
Composition
Composition
Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.
- It represents part-of relationship.
- In composition, both the entities are dependent on each other.
- When there is a composition between two entities, the composed object cannot exist without the other entity.
Aggregation vs Composition
- Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human
- Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
- Type of association: Composition is a strong Association whereas Aggregation is a weak Association.
Super keyword in java with example
The super keyword refers to the objects of immediate parent class
The use of super keyword
1) To access the data members of parent class when both parent and child class have member with same name
2) To explicitly call the no-arg and parameterized constructor of parent class
3) To access the method of parent class when child class has overridden that method.
1) How to use super keyword to access the variables of parent class
When you have a variable in child class which is already present in the parent class then in order to access the variable of parent class, you need to use the super keyword.
//Parent class or Superclass or base class
class Superclass
{
int num = 100;
}
//Child class or subclass or derived class
class Subclass extends Superclass
{
/* The same variable num is declared in the Subclass
* which is already present in the Superclass
*/
int num = 110;
void printNumber(){
System.out.println(num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Accessing the num variable of parent class:
By calling a variable like this, we can access the variable of parent class if both the classes (parent and child) have same variable.
super.variable_name
Let’s take the same example that we have seen above, this time in print statement we are passing super.num instead of num.
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
/* Note that instead of writing num we are
* writing super.num in the print statement
* this refers to the num variable of Superclass
*/
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
2) Use of super keyword to invoke constructor of parent class
When we create the object of sub class, the new keyword invokes the constructor of child class, which implicitly invokes the constructor of parent class. So the order to execution when we create the object of child class is: parent class constructor is executed first and then the child class constructor is executed. It happens because compiler itself adds super()(this invokes the no-arg constructor of parent class) as the first statement in the constructor of child class.
Parameterized super() call to invoke parameterized constructor of parent class
3) How to use super keyword in case of method overriding
When a child class declares a same method which is already present in the parent class then this is called method overriding. However by using super keyword like this: super.method_name you can call the method of parent class (the method which is overridden). In case of method overriding, these terminologies are used: Overridden method: The method of parent class Overriding method: The method of child class Lets take an example to understand this concept:
class Parentclass
{
//Overridden method
void display(){
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
//Overriding method
void display(){
System.out.println("Child class method");
}
void printMsg(){
//This would call Overriding method
display();
//This would call Overridden method
super.display();
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printMsg();
}
}
Method Overloading in Java with examples
Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Invalid case of method overloading:
When I say argument list, I am not talking about return type of the method, for example if two methods have same name, same parameters and have different return type, then this is not a valid method overloading example. This will throw compilation error.
int add(int, int)
float add(int, int)
Method overloading is an example of Static Polymorphism
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
Lets see few Valid/invalid cases of method overloading
Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having same number, data types and same sequence of data types.
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case of overloading. Here data types of arguments are different.
Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case of overloading. Here number of arguments are different.
Case 4:
float mymethod(int a, float b)
float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case of overloading. Sequence of the data types of parameters are different, first method is having (int, float) and second is having (float, int).
Case 5:
int mymethod(int a, int b)
float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even though return type of methods are different, it is not a valid case. Since return type of method doesn’t matter while overloading a method.
Guess the answers before checking it at the end of programs:
Question 1 – return type, method name and argument list same.
class Demo
{
public int myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4
{
public static void main(String args[])
{
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}
Answer:
It will throw a compilation error: More than one method with same name and argument list cannot be defined in a same class.
Question 2 – return type is different. Method name & argument list same.
class Demo2
{
public double myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5
{
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}
Answer:
It will throw a compilation error: More than one method with same name and argument list cannot be given in a class even though their return type is different. Method return type doesn’t matter in case of overloading.
Method overriding in java with example
Declaring a method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class.
Method Overriding Example
Lets take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The Boy class extends Human class. Both the classes have a common method void eat(). Boy class is giving its own implementation to the eat() method or in other words it is overriding the eat() method.
The purpose of Method Overriding is clear here. Child class wants to give its own implementation so that when it calls this method, it prints Boy is eating instead of Human is eating.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
Advantage of method overriding
The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class code.
Method Overriding is an example of runtime polymorphism.
Rules of method overriding in Java
- Argument list: The argument list of overriding method (method of child class) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match.
Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier,because all of these three access modifiers are more restrictive than public.
For e.g. This is not allowed as child class disp method is more restrictive(protected) than base class(public)
class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
protected void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: Cannot reduce the visibility of the inherited method from MyBaseClass
However this is perfectly valid scenario as public is less restrictive than protected. Same access modifier is also a valid one.
class MyBaseClass{
protected void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
public void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Output:
Child class method
- private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
- Overriding method (method of child class) can throw unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. We will discuss this in detail with example in the upcoming tutorial.
- Binding of overridden methods happen at runtime which is known as dynamic binding.
- If a class is extending an abstract class or implementing an interface then it has to override all the abstract methods unless the class itself is a abstract class.
Difference between method Overloading and Overriding in java
- Overloading happens at compile-time while Overriding happens at runtime
- Static methods can be overloaded which means a class can have more than one static method of same name. Static methods cannot be overridden, even if you declare a same static method in child class.
- The most basic difference is that overloading is being done in the same class while for overriding base and child classes are required.
- Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods.
- Performance: Overloading gives better performance compared to overriding. The reason is that the binding of overridden methods is being done at runtime.
- private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class.
- Return type of method does not matter in case of method overloading, it can be same or different. However in case of method overriding the overriding method can have more specific return type.
- Argument list should be different while doing method overloading. Argument list should be same in method Overriding.