What is Inheritance?

Inheritance is a mechanism in which one class acquires the property of another class. For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates Reusability and is an important concept of OOPs.

In this tutorial, you will learn-

Types of Inheritance

There are Various types of inheritance in Java:

  1. Single Inheritance:

In Single Inheritance one class extends another class (one class only).

Types of Inheritance

In above diagram, Class B extends only Class A. Class A is a super class and Class B is a Sub-class.

  1. Multiple Inheritance:

In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.

Types of Inheritance

As per above diagram, Class C extends Class A and Class B both.

  1. Multilevel Inheritance:

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived class becomes the base class for the new class.

Types of Inheritance

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.

  1. Hierarchical Inheritance:

In Hierarchical Inheritance, one class is inherited by many sub classes.

Types of Inheritance

As per above example, Class B, C, and D inherit the same class A.

  1. Hybrid Inheritance:

Hybrid inheritance is a combination of Single and Multiple inheritance.

Types of Inheritance

As per above example, all the public and protected members of Class A are inherited into Class D, first via Class B and secondly via Class C.

Note: Java doesn't support hybrid/Multiple inheritence

Inheritance in Java

  • In Java, when an "Is-A" relationship exists between two classes we use Inheritance
  • The parent class is termed super class and the inherited class is the sub class
  • The keyword "extends" is used by the sub class to inherit the features of super class
  • Inheritance is important since it leads to reusability of code

Java Inheritance Syntax:

class subClass extends superClass  
{  
   //methods and fields  
}  

Java Inheritance Example

Concept of Inheritance Java and Java Polymorphism

class Doctor {
 void Doctor_Details() {
  System.out.println("Doctor Details...");
 }
}

class Surgeon extends Doctor {
 void Surgeon_Details() {
  System.out.println("Surgen Detail...");
 }
}

public class Hospital {
 public static void main(String args[]) {
  Surgeon s = new Surgeon();
  s.Doctor_Details();
  s.Surgeon_Details();
 }
}

Super Keyword

The super keyword is similar to "this" keyword.

The keyword super can be used to access any data member or methods of the parent class.

Super keyword can be used at variable, method and constructor level.

Syntax:

super.<method-name>();

Learn Inheritance in OOP’s with Example

Consider the same banking application from the previous example.

We are supposed to open two different account types, one for saving and another for checking (also known as current).

Java Inheritance & Polymorphism

Let's compare and study how we can approach coding from a structured and object-oriented programming perspective.Structural approach: In structured programming, we will create two functions –

  1. One to withdraw
  2. And the other for deposit action.

Since the working of these functions remains same across the accounts.

Java Inheritance & Polymorphism

OOP's approach: While using the OOPs programming approach. We would create two classes.

  • Each having implementation of the deposit and withdraw functions.
  • This will redundant extra work.

Java Inheritance & Polymorphism

Change Request in Software

Now there is a change in the requirement specification for something that is so common in the software industry. You are supposed to add functionality privileged Banking Account with Overdraft Facility. For a background, overdraft is a facility where you can withdraw an amount more than available the balance in your account.

Java Inheritance & Polymorphism

Structural approach: Using functional approach, I have to modify my withdraw function, which is already tested and baselined. And add a method like below will take care of new requirements.

Java Inheritance & Polymorphism

OOP's approach: Using OOP's approach, you just need to write a new class with unique implementation of withdraw function. We never touched the tested piece of code.

Java Inheritance & Polymorphism

Another Change Request

What if the requirement changes further? Like to add credit card account with its own unique requirement of deposits.

Java Inheritance & Polymorphism

Structural approach: Using structural approach you have to change tested piece of deposit code again.

Java Inheritance & Polymorphism

OOP's approach: But using object-oriented approach, you will just create a new class with its unique implementation of deposit method ( highlighted red in the image below).

So even though the structural programming seems like an easy approach initially, OOP's wins in a long term.

Java Inheritance & Polymorphism

Advantage of Inheritance in OOPs

But one may argue that across all classes, you have a repeated pieces of code.

To overcome this, you create a parent class, say "account" and implement the same function of deposit and withdraw. And make child classes inherited "account" class. So that they will have access to withdraw and deposit functions in account class.

The functions are not required to be implemented individually. This is Inheritance in java. .

Java Inheritance & Polymorphism

Java Inheritance & Polymorphism

************************************************************************************************************************************************************

Inheritance in Java

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.
Important terminology:

  • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

How to use inheritance in Java

The keyword used for inheritance is extends.
Syntax :

class derived-class extends base-class  
{  
   //methods and fields  
}  

Example: In below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class which extends Bicycle class and class Test is a driver class to run program.

filter_none

edit

play_arrow

brightness_4

//Java program to illustrate the 
// concept of inheritance
 
// base class
classBicycle 
{
    // the Bicycle class has two fields
    publicintgear;
    publicintspeed;
         
    // the Bicycle class has one constructor
    publicBicycle(intgear, intspeed)
    {
        this.gear = gear;
        this.speed = speed;
    }
         
    // the Bicycle class has three methods
    publicvoidapplyBrake(intdecrement)
    {
        speed -= decrement;
    }
         
    publicvoidspeedUp(intincrement)
    {
        speed += increment;
    }
     
    // toString() method to print info of Bicycle
    publicString toString() 
    {
        return("No of gears are "+gear
                +"\n"
                + "speed of bicycle is "+speed);
    
}
 
// derived class
classMountainBike extendsBicycle 
{
     
    // the MountainBike subclass adds one more field
    publicintseatHeight;
 
    // the MountainBike subclass has one constructor
    publicMountainBike(intgear,intspeed,
                        intstartHeight)
    {
        // invoking base-class(Bicycle) constructor
        super(gear, speed);
        seatHeight = startHeight;
    
         
    // the MountainBike subclass adds one more method
    publicvoidsetHeight(intnewValue)
    {
        seatHeight = newValue;
    
     
    // overriding toString() method
    // of Bicycle to print more info
    @Override
    publicString toString()
    {
        return(super.toString()+
                "\nseat height is "+seatHeight);
    }
     
}
 
// driver class
publicclassTest 
{
    publicstaticvoidmain(String args[]) 
    {
         
        MountainBike mb = newMountainBike(3, 100, 25);
        System.out.println(mb.toString());
             
    }
}

Output:

No of gears are 3
speed of bicycle is 100
seat height is 25

In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass acquire memory in this object. That is why, by using the object of the subclass we can also access the members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass. For more, referJava Object Creation of Inherited Class.
Illustrative image of the program: 
f

In practice, inheritance and polymorphism are used together in java to achieve fast performance and readability of code.

Types of Inheritance in Java

Below are the different types of inheritance which is supported by Java.

    1. Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B.

      Single_Inheritance

      filter_none

      edit

      play_arrow

      brightness_4

      //Java program to illustrate the 
      // concept of single inheritance
      importjava.util.*;
      importjava.lang.*;
      importjava.io.*;
       
      classone
      {
          publicvoidprint_geek()
          {
              System.out.println("Geeks");
          }
      }
       
      classtwo extendsone
      {
          publicvoidprint_for()
          {
              System.out.println("for");
          }
      }
      // Driver class
      publicclassMain
      {
          publicstaticvoidmain(String[] args)
          {
              two g = newtwo();
              g.print_geek();
              g.print_for();
              g.print_geek();
          }
      }

      Output:

      Geeks
      for
      Geeks
      
    1. Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.

      Multilevel_Inheritance

      filter_none

      edit

      play_arrow

      brightness_4

      // Java program to illustrate the 
      // concept of Multilevel inheritance
      importjava.util.*;
      importjava.lang.*;
      importjava.io.*;
       
      classone
      {
          publicvoidprint_geek()
          {
              System.out.println("Geeks");
          }
      }
       
      classtwo extendsone
      {
          publicvoidprint_for()
          {
              System.out.println("for");
          }
      }
       
      classthree extendstwo
      {
          publicvoidprint_geek()
          {
              System.out.println("Geeks");
          }
      }
       
      // Drived class
      publicclassMain
      {
          publicstaticvoidmain(String[] args)
          {
              three g = newthree();
              g.print_geek();
              g.print_for();
              g.print_geek();
          }
      }

      Output:

      Geeks
      for
      Geeks
      
    2. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub class.In below image, the class A serves as a base class for the derived class B,C and D.

hie

filter_none

edit

play_arrow

brightness_4

// Java program to illustrate the 
// concept of Hierarchical inheritance
importjava.util.*;
importjava.lang.*;
importjava.io.*;
 
classone
{
    publicvoidprint_geek()
    {
        System.out.println("Geeks");
    }
}
 
classtwo extendsone
{
    publicvoidprint_for()
    {
        System.out.println("for");
    }
}
 
classthree extendsone
{
    /*............*/
}
 
// Drived class
publicclassMain
{
    publicstaticvoidmain(String[] args)
    {
        three g = newthree();
        g.print_geek();
        two t = newtwo();
        t.print_for();
        g.print_geek();
    }
}

Output:

Geeks
for
Geeks
    1. Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritance with classes. In java, we can achieve multiple inheritance only through Interfaces. In image below, Class C is derived from interface A and B.

      Multiple_Inheritance

      filter_none

      edit

      play_arrow

      brightness_4

      // Java program to illustrate the 
      // concept of Multiple inheritance
      importjava.util.*;
      importjava.lang.*;
      importjava.io.*;
        
      interfaceone
      {
          publicvoidprint_geek();
      }
        
      interfacetwo
      {
          publicvoidprint_for();
      }
        
      interfacethree extendsone,two
      {
          publicvoidprint_geek();
      }
      classchild implementsthree
      {
          @Override
          publicvoidprint_geek() {
              System.out.println("Geeks");
          }
        
          publicvoidprint_for()
          {
              System.out.println("for");
          }
      }
       
      // Drived class
      publicclassMain
      {
          publicstaticvoidmain(String[] args)
          {
              child c = newchild();
              c.print_geek();
              c.print_for();
              c.print_geek();
          }
      }

      Output:

      Geeks
      for
      Geeks
      
    2. Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

      hybrid

Important facts about inheritance in Java

  • Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.
  • Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have only one superclass. This is because Java does not support multiple inheritance with classes. Although with interfaces, multiple inheritance is supported by java.
  • Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
  • Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be used by the subclass.

What all can be done in a Subclass?

In sub-classes we can inherit members as is, replace them, hide them, or supplement them with new members:

  • The inherited fields can be used directly, just like any other fields.
  • We can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • We can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it (as in example above, toString() method is overridden).
  • We can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • We can declare new methods in the subclass that are not in the superclass.
  • We can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

***********************************************************************************************************************************************************

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. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists.

let’s get back to the point, when I say argument list it means the parameters that a method has: For example the argument list of a method add(int a, int b) having two parameters is different from the argument list of the method add(int a, int b, int c) having three parameters.

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. We will discuss polymorphism and types of it in a separate tutorial.

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.

Method Overloading examples

As discussed in the beginning of this guide, method overloading is done by declaring same method with different parameters. The parameters must be different in either of these: number, sequence or types of parameters (or arguments). Lets see examples of each of these cases.

Argument list is also known as parameter list

Example 1: Overloading – Different Number of parameters in argument list

This example shows how method overloading is done by having different number of parameters

class DisplayOverloading
{
    public void disp(char c)
    {
         System.out.println(c);
    }
    public void disp(char c, int num)  
    {
         System.out.println(c + " "+num);
    }
}
class Sample
{
   public static void main(String args[])
   {
       DisplayOverloading obj = new DisplayOverloading();
       obj.disp('a');
       obj.disp('a',10);
   }
}

Output:

a
a 10

In the above example – method disp() is overloaded based on the number of parameters – We have two methods with the name disp but the parameters they have are different. Both are having different number of parameters.

Example 2: Overloading – Difference in data type of parameters

In this example, method disp() is overloaded based on the data type of parameters – We have two methods with the name disp(), one with parameter of char type and another method with the parameter of int type.

class DisplayOverloading2
{
    public void disp(char c)
    {
        System.out.println(c);
    }
    public void disp(int c)
    {
       System.out.println(c );
    }
}

class Sample2
{
    public static void main(String args[])
    {
        DisplayOverloading2 obj = new DisplayOverloading2();
        obj.disp('a');
        obj.disp(5);
    }
}

Output:

a
5

Example3: Overloading – Sequence of data type of arguments

Here method disp() is overloaded based on sequence of data type of parameters – Both the methods have different sequence of data type in argument list. First method is having argument list as (char, int) and second is having (int, char). Since the sequence is different, the method can be overloaded without any issues.

class DisplayOverloading3
{
   public void disp(char c, int num)
   {
       System.out.println("I’m the first definition of method disp");
   }
   public void disp(int num, char c)
   {
       System.out.println("I’m the second definition of method disp" );
   }
}
class Sample3
{
   public static void main(String args[])
   {
       DisplayOverloading3 obj = new DisplayOverloading3();
       obj.disp('x', 51 );
       obj.disp(52, 'y');
   }
}

Output:

Im the first definition of method disp
Im the second definition of method disp

Method Overloading and Type Promotion

When a data type of smaller size is promoted to the data type of bigger size than this is called type promotion, for example: byte data type can be promoted to short, a short data type can be promoted to int, long, double etc.

What it has to do with method overloading?
Well, it is very important to understand type promotion else you will think that the program will throw compilation error but in fact that program will run fine because of type promotion.
Lets take an example to see what I am talking here:

class Demo{
   void disp(int a, double b){
	System.out.println("Method A");
   }
   void disp(int a, double b, double c){
	System.out.println("Method B");
   }
   public static void main(String args[]){
	Demo obj = new Demo();
	/* I am passing float value as a second argument but
	 * it got promoted to the type double, because there
	 * wasn't any method having arg list as (int, float)
	 */
	obj.disp(100, 20.67f);
   }
}

Output:

Method A

As you can see that I have passed the float value while calling the disp() method but it got promoted to the double type as there wasn’t any method with argument list as (int, float)

But this type promotion doesn’t always happen, lets see another example:

class Demo{
   void disp(int a, double b){
	System.out.println("Method A");
   }
   void disp(int a, double b, double c){
	System.out.println("Method B");
   }
   void disp(int a, float b){
	System.out.println("Method C");
   }
   public static void main(String args[]){
	Demo obj = new Demo();
	/* This time promotion won't happen as there is
	 * a method with arg list as (int, float)
	 */
	obj.disp(100, 20.67f);
   }
}

Output:

Method C

As you see that this time type promotion didn’t happen because there was a method with matching argument type.
Type Promotion table: 
The data type on the left side can be promoted to the any of the data type present in the right side of it.

byte  short  int  long
short  int  long
int  long  float  double
float  double
long  float  double

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. In this case the method in parent class is called overridden method and the method in child class is called overriding method. In this guide, we will see what is method overriding in Java and why we use it.

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.

This is helpful when a class has several child classes, so if a child class needs to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code.

Method Overriding and Dynamic Method Dispatch

Method Overriding is an example of runtime polymorphism. When a parent class reference points to the child class object then the call to the overridden method is determined at runtime, because during method call which method(parent class or child class) is to be executed is determined by the type of object. This process in which call to the overridden method is resolved at runtime is known as dynamic method dispatch. Lets see an example to understand this:

class ABC{
   //Overridden method
   public void disp()
   {
	System.out.println("disp() method of parent class");
   }	   
}
class Demo extends ABC{
   //Overriding method
   public void disp(){
	System.out.println("disp() method of Child class");
   }
   public void newMethod(){
	System.out.println("new method of child class");
   }
   public static void main( String args[]) {
	/* When Parent class reference refers to the parent class object
	 * then in this case overridden method (the method of parent class)
	 *  is called.
	 */
	ABC obj = new ABC();
	obj.disp();

	/* When parent class reference refers to the child class object
	 * then the overriding method (method of child class) is called.
	 * This is called dynamic method dispatch and runtime polymorphism
	 */
	ABC obj2 = new Demo();
	obj2.disp();
   }
}

Output:

disp() method of parent class
disp() method of Child class

In the above example the call to the disp() method using second object (obj2) is runtime polymorphism (or dynamic method dispatch).
Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class. In the above example the object obj2 is calling the disp(). However if you try to call the newMethod() method (which has been newly declared in Demo class) using obj2 then you would give compilation error with the following message:

Exception in thread "main" java.lang.Error: Unresolved compilation 
problem: The method xyz() is undefined for the type ABC

Rules of method overriding in Java

  1. 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.
  2. 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
  3. 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.
  4. 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.
  5. Binding of overridden methods happen at runtime which is known as dynamic binding.
  6. 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.

Super keyword in Method Overriding

The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the myMethod() method of base class while super() calls the constructor of base class. Let’s see the use of super in method Overriding.
As we know that we we override a method in child class, then call to the method using child class object calls the overridden method. By using super we can call the overridden method as shown in the example below:

class ABC{
   public void myMethod()
   {
	System.out.println("Overridden method");
   }	   
}
class Demo extends ABC{
   public void myMethod(){
	//This will call the myMethod() of parent class
	super.myMethod();
	System.out.println("Overriding method");
   }
   public static void main( String args[]) {
	Demo obj = new Demo();
	obj.myMethod();
   }
}

Output:

Class ABC: mymethod()
Class Test: mymethod()

As you see using super keyword, we can access the overriden method.

***********************************************************************************************************************************************************

Java Method Overriding Examples and Concepts: Overriding Rules

Method Overriding Examples and Concepts

Last week I wrote Java Method Hiding and Overriding: Override Static Method in Java here.

But I realized, it’s worth sharing some more information on Java Method Overriding.

Rules for method overriding:

  • In java, a method can only be written in Subclass, not in same class.
  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
  • The access level cannot be more restrictive than the overridden method’s access level.
    • For example: if the super class method is declared public then the over-ridding method in the sub class cannot be either private or protected.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited then it cannot be overridden.
  • A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not.
    • However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden.

Sample Example:

Result:

In the above example you can see that the even though b is a type of Company it runs the move method in the eBay class.

Reason: In compile time the check is made on the reference type. However in the runtime JVM figures out the object type and would run the method that belongs to that particular object.

Therefore in the above example, the program will compile properly since Company class has the method move. Then at the runtime it runs the method specific for that object.

Using the super keyword:

When invoking a superclass version of an overridden method the super keyword is used.

Result:

*************************************************************************************************************************************************************

Constructors in Java – A complete study!!

Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer constructor as special type of method in Java.

Constructor has same name as the class and looks like this in a java code.

public class MyClass{
   //This is the constructor
   MyClass(){
   }
   ..
}

Note that the constructor name matches with the class name and it doesn’t have a return type.

How does a constructor work

To understand the working of constructor, lets take an example. lets say we have a class MyClass.
When we create the object of MyClass like this:

MyClass obj = new MyClass()

The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object.

You may get a little lost here as I have not shown you any initialization example, lets have a look at the code below:

A simple constructor program in java

Here we have created an object obj of class Hello and then we displayed the instance variable nameof the object. As you can see that the output is BeginnersBook.com which is what we have passed to the name during initialization in constructor. This shows that when we created the object obj the constructor got invoked. In this example we have used this keyword, which refers to the current object, object obj in this example. We will cover this keyword in detail in the next tutorial.

public class Hello {
   String name;
   //Constructor
   Hello(){
      this.name = "BeginnersBook.com";
   }
   public static void main(String[] args) {
      Hello obj = new Hello();
      System.out.println(obj.name);
   }
}

Output:

BeginnersBook.com

new keyword invoked the constructor

Types of Constructors

There are three types of constructors: Default, No-arg constructor and Parameterized.
types of constructor

Default constructor

If you do not implement any constructor in your class, Java compiler inserts a default constructorinto your code on your behalf. This constructor is known as default constructor. You would not find it in your source code(the java file) as it would be inserted into the code during compilation and exists in .class file. This process is shown in the diagram below:
default constructor

If you implement any constructor then you no longer receive a default constructor from Java compiler.

no-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty.

Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you have written the code of it.

Example: no-arg constructor

class Demo
{
     public Demo()
     {
         System.out.println("This is a no argument constructor");
     }
     public static void main(String args[]) {
    	 new Demo();
     }
}

Output:
This is a no argument constructor

Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.

Example: parameterized constructor

In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1 and obj2.

public class Employee {

   int empId;  
   String empName;  
	    
   //parameterized constructor with two parameters
   Employee(int id, String name){  
       this.empId = id;  
       this.empName = name;  
   }  
   void info(){
        System.out.println("Id: "+empId+" Name: "+empName);
   }  
	   
   public static void main(String args[]){  
	Employee obj1 = new Employee(10245,"Chaitanya");  
	Employee obj2 = new Employee(92232,"Negan");  
	obj1.info();  
	obj2.info();  
   }  
}

Output:

Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

Example2: parameterized constructor

In this example, we have two constructors, a default constructor and a parameterized constructor. When we do not pass any parameter while creating the object using new keyword then default constructor is invoked, however when you pass a parameter then parameterized constructor that matches with the passed parameters list gets invoked.

class Example2
{
      private int var;
      //default constructor
      public Example2()
      {
             this.var = 10;
      }
      //parameterized constructor
      public Example2(int num)
      {
             this.var = num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example2 obj = new Example2();
              Example2 obj2 = new Example2(100);
              System.out.println("var is: "+obj.getValue());
              System.out.println("var is: "+obj2.getValue());
      }
}

Output:

var is: 10
var is: 100

What if you implement only parameterized constructor in class

class Example3
{
      private int var;
      public Example3(int num)
      {
             var=num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example3 myobj = new Example3();
              System.out.println("value of var is: "+myobj.getValue());
      }
}

Output: It will throw a compilation error. The reason is, the statement Example3 myobj = new Example3() is invoking a default constructor which we don’t have in our program. when you don’t implement any constructor in your class, compiler inserts the default constructor into your code, however when you implement any constructor (in above example I have implemented parameterized constructor with int parameter), then you don’t receive the default constructor by compiler into your code.

If we remove the parameterized constructor from the above code then the program would run fine, because then compiler would insert the default constructor into your code.

Constructor Chaining

When A constructor calls another constructor of same class then this is called constructor chaining. Read more about it here.
constructor chaining

Super()

Whenever a child class constructor gets invoked it implicitly invokes the constructor of parent class. You can also say that the compiler inserts a super(); statement at the beginning of child class constructor.

class MyParentClass {
   MyParentClass(){
	System.out.println("MyParentClass Constructor");
   }
}
class MyChildClass extends MyParentClass{
   MyChildClass() {
	System.out.println("MyChildClass Constructor");
   }
   public static void main(String args[]) {
	new MyChildClass();
   }
}

Output:

MyParentClass Constructor
MyChildClass Constructor

Read more about super keyword here.

Constructor Overloading

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.
constructor overloading

Refer constructor overloading with example for more details with example.

Java Copy Constructor

A copy constructor is used for copying the values of one object to another object.

class JavaExample{  
   String web; 
   JavaExample(String w){  
	web = w;
   }  

   /* This is the Copy Constructor, it 
    * copies the values of one object
    * to the another object (the object
    * that invokes this constructor)
    */
   JavaExample(JavaExample je){  
	web = je.web; 
   }  
   void disp(){
	System.out.println("Website: "+web);
   }  

   public static void main(String args[]){  
	JavaExample obj1 = new JavaExample("BeginnersBook");  
		
	/* Passing the object as an argument to the constructor
	 * This will invoke the copy constructor
	 */
	JavaExample obj2 = new JavaExample(obj1);  
	obj1.disp();  
	obj2.disp();  
   }  
}

Output:

Website: BeginnersBook
Website: BeginnersBook

Quick Recap

  1. Every class has a constructor whether it’s a normal class or a abstract class.
  2. Constructors are not methods and they don’t have any return type.
  3. Constructor name should match with class name .
  4. Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in java but there scope is within the class only.
  5. Like constructors method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.
  6. If you don’t implement any constructor within the class, compiler will do it for.
  7. this() and super() should be the first statement in the constructor code. If you don’t mention them, compiler does it for you accordingly.
  8. Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.
  9. Constructors can not be inherited.
  10. If Super class doesn’t have a no-arg(default) constructor then compiler would not insert a default constructor in child class as it does in normal scenario.
  11. Interfaces do not have constructors.
  12. Abstract class can have constructor and it gets invoked when a class, which implements interface, is instantiated. (i.e. object creation of concrete class).
  13. A constructor can also invoke another constructor of the same class – By using this(). If you want to invoke a parameterized constructor then do it like this: this(parameter list).

More on Constructor:

Difference between Constructor and Method

I know I should have mentioned it at the beginning of this guide but I wanted to cover everything in a flow. Hope you don’t mind 🙂

  1. The purpose of constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code.
  2. Constructors cannot be abstract, final, static and synchronised while methods can be.
  3. Constructors do not have return types while methods do.

************************************************************************************************************************************************************

method overloading

Screen Shot 2019-09-24 at 5.43.13 PM

Inheritance-Single

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package inheritance1;

/**
 *
 * @author Sushrut S P
 */
class Emp {
     int sal=4000;
 void Emp_Details() {
    
  //System.out.println("Doctor Details...");
 }
}

class Jd extends Emp {
      int bonus=10000;
 void Jd_Details() {
   //  int sum =sal+bonus;
   
  //System.out.println("Surgen Detail...");
 }
}

class Pty extends Emp{
int bonus =20000;
void Pty_Details(){


}

}

public class Inheritance1 {
 public static void main(String args[]) {
     
     
     
  Jd j= new Jd();
  Pty p=new Pty();
  j.Emp_Details();
  j.Jd_Details();
p.Pty_Details();
    System.out.println("Empolyee basic salary..."+ (j.sal+j.bonus));
  System.out.println("Python developer net salary..."+ (j.sal+p.bonus));
 }
}
    
    
    
    
    
 //In this programe no of developer requires different child classes,objects,methods  




Output: by netbeans



run:
Empolyee basic salary...14000
Python developer net salary...24000
BUILD SUCCESSFUL (total time: 0 seconds)






 

Inheritance

Concept - Array Difficulty Level 1

Create a class Library with below attributes:

int - id

String - name

String - address

Make all the attributes private.Create corresponding getters and setters.

Create a constructor which takes all parameters in the above sequence. The constructor should set the value of attributes to parameter values inside the constructor.

Create a class LibraryDemo with main method

Create the below static method searchLibraryById in the LibraryDemo class.

searchLibraryById(Library[] objArray)

This method will take array of Library objects and id as input and returns the position of the id if found or -1 if not found.

Create an array of 5 Library objects in the main method
Refer below sample main method and test the output:

Call the above static method from the main method


public class LibraryDemo {
public static void main(String args[]){
Library library1= new Library(27,"vjxiyhc","kyoyfsl");
Library library2= new Library(34,"oguybhh","cuaxany");
Library library3= new Library(10,"oxhdjcs","gvhtlzw");
Library library4= new Library(19,"thamkrf","arijclh");
Library library5= new Library(32,"cvljyye","heijkiv");


Library[] objArray= {library1,library2,library3,library4,library5};

int libraryres= searchLibraryById(objArray, 59);
System.out.println("Output after first search: "+libraryres);

int libraryres1= searchLibraryById(objArray, 34);
System.out.println("Output after second search: "+libraryres1);
}}
Output
Output after first search: -1
Output after second search: 1

In First Programe Search ID 59 it shows the -1
Again, in Second Search ID 34 it shows the 1.
Execute the both programes seprately

Programme for output search: -1

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package librarydemo;

/**
 *
 * @author Sonu Kumar
 */



 class Library {

    private int id;
    private String name;
   private String address;

    public Library(int id, String name,String address){
        this.id=id;
        this.name=name;
        this.address=address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {

        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}




public class LibraryDemo {

  public static int searchLibraryById(Library[] objArray,int x){
        int res;
      int check=-1;

        for(int i=0;i<5;i++){
           res= objArray[i].getId();

            if(res==x){

                check=1;
            }

        }
        return check;
    }

    public static void main(String arg[]){

       //Library[] objArray=new Library[5];

        Library library1= new Library(27,"vjxiyhc","kyoyfsl");
        Library library2= new Library(34,"oguybhh","cuaxany");
        Library library3= new Library(10,"oxhdjcs","gvhtlzw");
        Library library4= new Library(19,"thamkrf","arijclh");
        Library library5= new Library(32,"cvljyye","heijkiv");

        Library[] objArray= {library1,library2,library3,library4,library5};

        int libraryres= searchLibraryById(objArray, 59);
        System.out.println("Output after first search: "+libraryres);
    }
    
}
run:
Output after first search: -1
BUILD SUCCESSFUL (total time: 0 seconds)

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package librarydemo;
/**
 *
 * @author Sonu Kumar
 */
 class Library {
    private int id;
    private String name;
   private String address;
    public Library(int id, String name,String address){
        this.id=id;
        this.name=name;
        this.address=address;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
public class LibraryDemo {
  public static int searchLibraryById(Library[] objArray,int x){
        int res;
      int check=-1;
        for(int i=0;i<5;i++){
           res= objArray[i].getId();
            if(res==x){
                check=1;
            }
        }
        return check;
    }
    public static void main(String arg[]){
       //Library[] objArray=new Library[5];
        Library library1= new Library(27,"vjxiyhc","kyoyfsl");
        Library library2= new Library(34,"oguybhh","cuaxany");
        Library library3= new Library(10,"oxhdjcs","gvhtlzw");
        Library library4= new Library(19,"thamkrf","arijclh");
        Library library5= new Library(32,"cvljyye","heijkiv");
        Library[] objArray= {library1,library2,library3,library4,library5};
        int libraryres= searchLibraryById(objArray, 34);
        System.out.println("Output after first search: "+libraryres);
    }
    
}
run:
Output after first search: 1
BUILD SUCCESSFUL (total time: 0 seconds)

 

Concept - Array Difficulty Level 2

Create a class Library with below attributes:

int - id

String - name

String - address

Make all the attributes private.Create corresponding getters and setters.

Create a constructor which takes all parameters in the above sequence. The constructor should set the value of attributes to parameter values inside the constructor.

Create a class LibraryDemo with main method

Create a static method replaceLibraryById in the LibraryDemo class. This method will take array of Library objects and one Library object as input. Replace the Library object with same id if found in the array and return true. Else return false

Create an array of 5 Library objects in the main method
Refer below sample main method and test the output:

Call the above static method from the main method

public class LibraryDemo {
public static void main(String args[]){
Library library1= new Library(33,"drfnfuk","cqisthj");
Library library2= new Library(78,"xhzebcf","nnpwbrf");
Library library3= new Library(68,"qnoquku","qstcebj");
Library library4= new Library(81,"ghgwsjm","xlewgbj");
Library library5= new Library(47,"wgioqsg","vjtwscm");

Library[] objArray= {library1,library2,library3,library4,library5};
Library libraryRes1= new Library(18,"rmgjynm","qxkhlbb");

boolean result= replaceLibraryById(objArray, libraryRes1);
System.out.println("Output for performing replace on libraryRes1 is: "+ result );

System.out.println("Displaying contents of array: ");

for(Library library:objArray){
System.out.println(library.getId()+" " + library.getName()+" " + library.getAddress()+" ");
}
System.out.println();

Library libraryRes2= new Library(47,"tvistro","rnpholx");
result= replaceLibraryById(objArray, libraryRes2);

System.out.println("Output for performing replace on libraryRes2 is: "+ result );

System.out.println("Displaying contents of array: ");

for(Library library:objArray){
System.out.println(library.getId()+" " + library.getName()+" " + library.getAddress()+" ");
}
}}
Output
Output for performing replace on libraryRes1 is: false
Displaying contents of array:
33 drfnfuk cqisthj
78 xhzebcf nnpwbrf
68 qnoquku qstcebj
81 ghgwsjm xlewgbj
47 wgioqsg vjtwscm

Output for performing replace on libraryRes2 is: true
Displaying contents of array:
33 drfnfuk cqisthj
78 xhzebcf nnpwbrf
68 qnoquku qstcebj
81 ghgwsjm xlewgbj
47 tvistro rnpholx

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package librarydemo;

class Library {

private int id;
private String name;
private String address;

public Library(int id, String name,String address){
this.id=id;
this.name=name;
this.address=address;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {

return address;
}

public void setAddress(String address) {
this.address = address;
}
}

public class LibraryDemo {

public static boolean replaceLibraryById(Library[] objArray,Library libraryRes1){

int res;
boolean bres=false;

for(int i=0;i<5;i++){
res=objArray[i].getId();
if(res==libraryRes1.getId()){
bres=true;
objArray[i].setName(libraryRes1.getName());
objArray[i].setAddress(libraryRes1.getAddress());

}
else
bres=false;
}
return bres;
}

public static void main(String arg[]){

//Library[] objArray=new Library[5];

Library library1= new Library(33,"drfnfuk","cqisthj");
Library library2= new Library(78,"xhzebcf","nnpwbrf");
Library library3= new Library(68,"qnoquku","qstcebj");
Library library4= new Library(81,"ghgwsjm","xlewgbj");
Library library5= new Library(47,"tvistro","rnpholx");

Library[] objArray= {library1,library2,library3,library4,library5};
Library libraryRes1= new Library(18,"rmgjynm","qxkhlbb");

boolean result= replaceLibraryById(objArray, libraryRes1);
System.out.println("Outputperforming replace on libraryRes1 is: "+ result );

System.out.println("Displayingents of array: ");

for(Library library:objArray){
System.out.println(library.getId()+" " + library.getName()+" " + library.getAddress()+" ");
}
System.out.println();


}
}

 

run:
Outputperforming replace on libraryRes1 is: false
Displayingents of array: 
33 drfnfuk cqisthj 
78 xhzebcf nnpwbrf 
68 qnoquku qstcebj 
81 ghgwsjm xlewgbj 
47 wgioqsg vjtwscm 

BUILD SUCCESSFUL (total time: 0 seconds)

 

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package librarydemo;



class Library {

   private int id;
    private String name;
     private String address;

    public Library(int id, String name,String address){
        this.id=id;
        this.name=name;
        this.address=address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {

        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}



public class LibraryDemo {

    public static boolean replaceLibraryById(Library[] objArray,Library libraryRes1){

        int res;
        boolean bres=false;

        for(int i=0;i<5;i++){
            res=objArray[i].getId();
            if(res==libraryRes1.getId()){
                bres=true;
                objArray[i].setName(libraryRes1.getName());
                objArray[i].setAddress(libraryRes1.getAddress());

            }
            else
                bres=false;
        }
        return bres;
    }

    public static void main(String arg[]){

       //Library[] objArray=new Library[5];

Library library1= new Library(33,"drfnfuk","cqisthj");
Library library2= new Library(78,"xhzebcf","nnpwbrf");
Library library3= new Library(68,"qnoquku","qstcebj");
Library library4= new Library(81,"ghgwsjm","xlewgbj");
Library library5= new Library(47,"wgioqsg","vjtwscm");

        Library[] objArray= {library1,library2,library3,library4,library5};
        Library libraryRes2= new Library(47,"tvistro","rnpholx");

        boolean result= replaceLibraryById(objArray, libraryRes2);
        System.out.println("Outputperforming replace on libraryRes1 is: "+ result  );

        System.out.println("Displayingents of array: ");

        for(Library library:objArray){
            System.out.println(library.getId()+" " + library.getName()+" " + library.getAddress()+" ");
        }
        System.out.println();




    }
}

 

run:
Outputperforming replace on libraryRes1 is: true
Displayingents of array: 
33 drfnfuk cqisthj 
78 xhzebcf nnpwbrf 
68 qnoquku qstcebj 
81 ghgwsjm xlewgbj 
47 tvistro rnpholx 

BUILD SUCCESSFUL (total time: 0 seconds)

 

Concept - Array Difficulty Level 2 (sort Libray by Name)

Create a class Library with below attributes:

int - id

String - name

String - address

Make all the attributes private.Create corresponding getters and setters.

Create a constructor which takes all parameters in the above sequence. The constructor should set the value of attributes to parameter values inside the constructor.

Create a class LibraryDemo with main method

Create the below static method sortLibraryByName in the LibraryDemo class.

sortLibraryByName(Library[] objArray)

The method will sort the array based on name and return the sorted array.

Create an array of 5 Library objects in the main method
Refer below sample main method and test the output:

Call the above static method from the main method

public class LibraryDemo {
public static void main(String args[]){
Library library1= new Library(20,"uksyjyf","rmbkcgl");
Library library2= new Library(63,"bobzxii","rpgfcvp");
Library library3= new Library(57,"hgggtcb","zaocydu");
Library library4= new Library(80,"vztbgaf","dpcupzm");
Library library5= new Library(27,"okhrsep","knogyfm");

Library[] objArray= {library1,library2,library3,library4,library5};

Library[] objArrayRes= sortLibraryByName(objArray);
System.out.println("Displaying contents of array: ");

for(Library library:objArray){
System.out.println(library.getId()+" " + library.getName()+" " + library.getAddress()+" ");
}
}}
Output
Displaying contents of array:
63 bobzxii rpgfcvp
57 hgggtcb zaocydu
27 okhrsep knogyfm
20 uksyjyf rmbkcgl
80 vztbgaf dpcupzm

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package librarydemo;


/**
 *
 * @author Sonu Kumar
 */

import java.io.*;
import java.lang.*;

 class Library
{
    private int id;
    private String name;
    private String address;
   
    public Library(int id, String name, String address)
    {
        this.id = id;
        this.name = name;
        this.address = address;
    }
    
     public int get_id()
    {
         return id;
    }
      public String get_name()
    {
         return name;
    }
      public String get_address()
    {
         return address;
    }

  

}

public class LibraryDemo
{
    public static void main(String args[])
    {
     Library library1= new Library(20,"uksyjyf","rmbkcgl");
Library library2= new Library(63,"bobzxii","rpgfcvp");
Library library3= new Library(57,"hgggtcb","zaocydu");
Library library4= new Library(80,"vztbgaf","dpcupzm");
Library library5= new Library(27,"okhrsep","knogyfm");


Library[] objArray= {library1,library2,library3,library4,library5};

Library[] objArrayRes= sortLibraryByName(objArray);
System.out.println("Displaying contents of array: ");

for(Library library:objArray){
System.out.println(library.get_id()+" " + library.get_name()+" " +
library.get_address()+" ");
}
    }
    public static Library[] sortLibraryByName(Library[] objArray)
    {
        for(int i=0;i<objArray.length;i++)
        {
           for(int j=0; j<objArray.length;j++)
           {
               if(objArray[i].get_name().compareTo(objArray[j].get_name()) < 0)
               {
                   Library temp = objArray[i];
                   objArray[i] = objArray[j];
                   objArray[j] = temp;
               }
           }

        }
        return objArray;
    }
}

OUTPUT

run:
Displaying contents of array: 
63 bobzxii rpgfcvp 
57 hgggtcb zaocydu 
27 okhrsep knogyfm 
20 uksyjyf rmbkcgl 
80 vztbgaf dpcupzm 
BUILD SUCCESSFUL (total time: 0 seconds)