Java ProgrammingLearn to implement polymorphism, inheritance, abstract methods, overriding and overloading in java

Learn to implement polymorphism, inheritance, abstract methods, overriding and overloading in java

In this tutorial we learn about how to implement interface, inheritance, abstract types, abstract methods, method overloading and method overriding using polymorphism also have brief look on dynamic binding using polymorphism.

  • To learn to implement polymorphism, inheritance, abstract methods, overriding and overloading in java follow the steps given below :

 

    1. Interface : – Interface is nothing but the collection of constant values and method definitions without implementations. In this case using an interface you can capture similarities between unrelated classes without forcing relationship between classes. A class can access only from one class but it can implement more than one interface. If we define a new interface you are defining a new reference data type. Functions of interface should be public and abstract. A class implementing an interface must use the keyword implements. Object of an interface cannot be created. Field of an interface must be final and public. Interface cannot be instantiated because interface does not have constructors.

Interface
Java Programming Course for Beginner From Scratch
Example : This example shows how an interface is used in a class.

class InterfaceDemo //create main class
{
//main method
public static void main(String[] args) 
{
//create object of class Student
Children chstud = new Student();
chstud.play();//call method
}
}
interface Children//create interface
{	
public void play();//declare method
}		
class Student implements Children//implements interface
{
public void play()//define method
{
System.out.println("Students are playing football");
}
}

Output :

Students are playing football

 

    1. Inheritance, Polymorphism and Abstract Types : –

 

      • Inheritance : – It is allows a class to inherit the properties of another class. When a class extends all the properties of another class it means that class inherits all non-private variables including methods and fields. It defines a “is-a” kind of relationship between Super class (Parent class) and Sub class (child class) in java language. To describe inheritance implements and extends keywords are used. It is helpful for reusability of code and purpose is too used for method overriding. The inheritance concept is also known as reusability classes.Types of Inheritance:

 

        1. Single Inheritance : – When one class inherit the properties of another one class only then it is called as single inheritance.

Inheritance

Example : This example shows how single inheritance is used in a class.

package Simpu;

class Parent 
{
 public void methodParent()//Parent class method
{
 System.out.println ("Parent class method is called..!");
}
}


package Simpu;

class Child extends Parent //inherit properties of Parent class
{
 public void methodChild()//Child class method
{
 System.out.println ("Child class method is called..!");
}
 public static void main(String args[])
{
 Child ch = new Child (); //create object of Child class
 ch.methodParent (); //calling super class method
 ch.methodChild ();   //calling local method
}	
}

Output :

Parent class method is called..!
Child class method is called..!

 

        1. Multilevel Inheritance : – The use of a derived class as a super class is common requirement in object-oriented programming. Java uses it extensively in building its class library and java also supports this concept. It allows us to build a chain of classes.

Multilevel Inheritance

Example : This example shows how multilevel inheritance is used in a class

package First;

class Top //create super class
{
protected String str;//define string
Top () // create constructor
{
str="P"; //declare str
}
}		
class Down1 extends Top//sub class1 extends super class
{
Down1 () // create constructor
{
str = str.concat("I");//concatenation of str
}
}


class Down2 extends Down1//sub class2 extends sub class1
{
Down2 () // create constructor
{
str = str.concat("Y");//concatenation of str
}
}


class Down3 extends Down2//sub class3 extends sub class2
{
Down3 () // create constructor
{	
str = str.concat("U");//concatenation of str
}
void show()//declare method
{
System.out.println (str); //print str
}
}	


class Test//create class to execute all classes
{
public static void main(String args[])
{	//create object of class Down3
Down3 d = new Down3 ();
d.show (); //call method show 
}
}

Output :

PIYU

 

        1. Hierarchical Inheritance : – It supports to the hierarchical design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below the level. It is one-to-many relationship.

Hierarchical Inheritance
Ultimate Java Development and Certification Course
Example : This example shows how hierarchical inheritance is used in a class.

package First;
public class Parent//base class
{
public void Parent()//super class constructor
{
System.out.println ("Method of Class Parent");
}
}


class Child1 extends Parent//subclass1 extends superclass
{
public void Child1() //subclass1 constructor
{
System.out.println ("Method of Class Child1");	
}
}


class Child2 extends Parent//subclass2 extends superclass
{
public void Child2()//subclass2 constructor
{
System.out.println ("Method of Class Child2");
}
}


class Child3 extends Parent//subclass3 extends superclass
{
public void Child3()//subclass3 constructor
{
System.out.println ("Method of Class Child3");
}
}


class MyClass//create class
{
public static void main(String args[])//main method
{
Child1 c1 = new Child1 (); //create object c1 of Child1
Child2 c2 = new Child2 (); //create object c2 of Child2
Child3 c3 = new Child3 (); //create object c3 of Child3
c1.Parent (); //call Parent class method with c1
c2.Parent (); //call Parent class method with c2
c3.Parent (); //call Parent class method with c3
}
}

Output :

Method of Class Parent
Method of Class Parent
Method of Class Parent

 

        1. Multiple Inheritance : – Java does not support multiple inheritances. So that reason java provides an alternate approach is called as interfaces, it supports the concept of multiple inheritances. Although a Java class does not be a subclass of more than one superclass, it can implement more than one interface without creating any problem.

Multiple Inheritance

        1. Hybrid Inheritance : – This is the combination of single inheritance and multiple inheritance. When hybrid inheritance supports multiple inheritance then hybrid inheritance not allowed.

Hybrid Inheritance

      • Polymorphism : It is nothing but the ability to take more than one form. This can be applied to both operations as well as objects. It is tightly coupled inheritance. It means one interface, many possible implementations.

Polymorphism

Two types of Polymorphism:

        1. Static Polymorphism: It is achieved through function overloading and operator overloading. It is always faster. It is also called as compile time polymorphism. Example of static polymorphism is method overriding using final or private methods. At the compilation time java knows which method is call by checking the arguments, so it is also known as early binding or static binding.

Types of static polymorphism :

          • Function Overloading: It is nothing but the ability of one function performs different tasks. These functions must differ by the data types. To call function the same function name is used for various instances.

Example : This example shows how function overloading is used in a java.

package MethodOverload;

class Children //create class
{
void student()//declare method without parameters
{
System.out.println("Students are playing");
}
//declare same method with parameter
void student(int rollno, String name)
{
System.out.println("Roll No: "+rollno+"\nName: "+name);
}
public static void main(String[] args)//main method
{
Children ch = new Children();//Create object of class
ch.student();//without parameters method call
ch.student(1, "Priya");//with parameters method call
ch.student(2, "Pranjal");
}
}

 

Students are playing
Roll No: 1
Name: Priya
Roll No: 2
Name: Pranjal

 

          • Operator Overloading : Java does not support operator overloading.

 

 

        1. Dynamic Polymorphism : It is also called as run-time polymorphism. In this case java compiler does not know which method is invoked at compilation time. Just JVM decides which method is invoked at the run-time. Method overriding is example of run-time polymorphism. In this case overridden method is invoking through the super class reference variable.

Types of Dynamic Polymorphism in java :

          • Virtual Function: This is nothing but the function whose performance can be overridden within an inheriting class by a function with the same argument or signature. Virtual function cannot be declared as private. In this function we get warning if we do not use Virtual or New keyword. You can use new keyword rather than Virtual.

Example : This example shows how dynamic polymorphism is used in a java.

package MethodOverride;

class Children //parent class
{
public void speak()//define method
{
System.out.println("Children speak in Hindi");				
}
}


class Student extends Children//extend parent class
{
public void speak()//override method
{
System.out.println("Students can speak in English");
}
}


class Test
{
public static void main(String[] args)//main method
{	//create object of Children and Student class
Children c1 = new Children();
Student s = new Student();
//call method speak
c1.speak();
s.speak();
}
}

Output :

Children speak in Hindi
Students can speak in English

 

 

      • Abstract : – When a class contains one or more abstract methods, then it should be declared abstract. You must use abstract keyword to make a class abstract. We cannot use abstract classes to instantiate objects directly. It needs to be extended and its method needs to be implemented. The abstract methods of an abstract class must be defined in its subclass. You cannot declare abstract constructors or abstract static methods. Abstract class have both method abstract as well as non-abstract methods. It also has a member variables and constructors.

Abstract Class

Example : This example shows how abstract is used in a java.

abstract class A //class declare as abstract
{	//declare method as abstract
abstract void callme();
}


class B extends A
{	//inherit callme method
void callme()
{
System.out.println("This is callme");
}
public static void main(String[] args) 
{	//create object of class B
B b = new B();
//call method
b.callme();
}
}

Output :

This is callme

 

 

    1. Overriding, Overloading and Abstract Methods : –

 

      • Method Overriding : Method overriding is nothing but the method in the child class should have the same name, same signature and parameters as the one in its parent class and also have the same return type. If a method declared final then it cannot be overridden. If a method declared static then it cannot be overridden but it can be re-declared. If a method cannot be inherited, then it cannot be overriden. It is used for runtime polymorphism. It must be is-a relationship. Polymorphism is applied on method overriding. It is a run-time concept. Abstract methods must be overridden. Constructors cannot be overridden. Dynamic binding is used for method overriding. Private and final method cannot be overridden.

Example : This example shows how method overriding is used in a java.

package MethodOverride;

class Children //parent class
{
public void play()//define method
{
System.out.println ("Children can play cricket");

}

class Student extends Children//extend parent class
{
public void play()//override method
{
System.out.println ("Students can play football");
}
}

class Test
{
public static void main(String[] args)//main method
{	//create object of Children and Student class
Children c1 = new Children ();
Student s = new Student ();
//call method play
c1.play ();
s.play ();
}
}

Output :

Children can play cricket
Students can play football

 

      • Method Overloading : It is nothing but in the same class, if name of the method remains same but the number and type of arguments or parameters are different, then it is called as method overloading. This concept is used for compile-time. Present in the same class. And can have different return types. It helps in maintain consistency in method naming, doing same task with different parameter. It helps to reduce overhead. It is also known as static polymorphism. Static method can be overloaded. Static binding is used for method overloading. It gives better performance than method overriding. Private and final methods can be overloaded. In method overloading return type should be same as the other methods of the same name. In method overloading argument list should be different.

Example : This example shows how method overloading is used in a java.

package MethodOverload;

class Children //create class
{
void student()//define method without parameters
{
System.out.println ("Students are playing");
}
//define same method with parameter
void student(int rollno, String name)
{
System.out.println ("Roll No: "+rollno+"\nName: "+name);
}
public static void main(String[] args)//main method
{
Children c = new Children (); //Create object of class
c.student (); //without parameters method call
c.student (101, "Priya"); //with parameters method call
}
}

Output :

Students are playing
Roll No: 101
Name: Priya

 

      • Abstract Method : Abstract method does not have any body. It is always ends with (;) semicolon. Abstract method must be overridden. It must be in an abstract class. It can never be static and final. Abstract methods are those which need to be implemented in subclass. If class has one abstract method then whole class is declared as abstract. Private method cannot be abstract.

Example : This example shows how abstract method is used in a class.

abstract class Calculator
{	  //define 2 integers
protected int no1;
protected int no2;
//declare abstract method
abstract int sum();
}  

class Addition extends Calculator//extends with Superclass
{
Addition (int n1, int n2)//constructor of Addition
{
no1 = n1;
no2 = n2;
}
int sum()//define method
{
return no1 + no2;//return Addition
}
}		

class Subtraction extends Calculator//extends with Superclass
{
Subtraction (int n1, int n2)//constructor of Subtraction
{
no1 = n1;
no2 = n2;
}
int sum()//define method
{
return no1 - no2;//return Subtraction
}
}

class Multiplication extends Calculator//extends with Superclass
{
Multiplication (int n1, int n2)//constructor of Multiplication
{
no1 = n1;
no2 = n2;
}
int sum()//define method
{
return no1 * no2;//return Multiplication
}
}

class AbstractMethodDemo
{
public static void main(String args[])//main method
{
Addition a = new Addition (5, 8); //Create object of Addition
Subtraction s = new Subtraction (32, 16); //Create object of    Subtraction
Multiplication m = new Multiplication (4, 2); //Create object of Multiplication

System.out.println ("Sum of Addition: " + a.sum ()); //Call method Addition
System.out.println ("Sum of Subtraction: " + s.sum ()); //call method Subtraction
System.out.println ("Sum of Multiplication: " + m.sum ()); //call method Multiplication
}
}

Output :

Sum of Addition : 13
Sum of Subtraction : 16
Sum of Multiplication : 8

 

 

    1. Dynamic Binding : – In java dynamic binding occurs during runtime. Dynamic binding uses object to resolve binding. It is also known as late binding. Only virtual methods are resolved using dynamic binding. True polymorphism is achieved using dynamic binding.

Example : This example shows how dynamic binding is used in a java.

class ITCompany
{
public void display() //create method
{
System.out.println ("This is all over IT Company Employee");
}
}

class TCS extends ITCompany//extends ITCompany
{	//Override method display
public void display()
{
System.out.println ("This is TCS Company Employee");
}
}

class Employee 
{	//main method
public static void main(String[] args) 
{	//type is ITCompany but object will be TCS
ITCompany ic = new TCS ();
ic.display (); //call method inside TCS
}
}

Output :

This is TCS Company Employee

 

  • Hence, we successfully learnt how to implement interface, inheritance, abstract types, abstract methods, method overloading, method overriding and dynamic binding using polymorphism in java.

3 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -