If you have a method that you want to use in different classes. Inheritance in java gives the opportunity to make the method once. As a consequence it is not necessary to rewrite or change the method in every class. You make the particular method once and it will work in every class that you will use it in.

Example:

You got a lot of pets and you want to safe their characteristics. One way to do this is categorise their characteristics. So for example. If you want to know the color of your pets. You could do it like this but it will cost more time when you got a lot of different pets.

Class 1 for dogs
package Inheritence;

public class dog {

	void color () {
		System.out.println("color = black");
	}

}
Class 2 for cats
package Inheritence;

public class cat {

	void color () {
		System.out.println("color = black");
	}

}

 

 

Class 3 is the main method in which you could ask what the color is
package Inheritence;

public class pets {

	
	void start() {
		dog myDog = new dog();
		cat myCat = new cat();
		
		myDog.color();
		myCat.color();
	}
	
	public static void main(String[] args) {
		new pets().start();

	}

}

As mentioned in the intro it is possible to do it more easily, by categorising the pets.

This is inheritance

(and for this example the easiest way to safe the data)

Make a fourth class, also called the SUPER class:

Class 4 which contain all the characteristics of your black pets ( in this case one characteristic = color )
package Inheritence;

public class blackPets {

	void color () {
		System.out.println("color = black");
	}

}

Now you could erase line 5,6,7 in the classes dog and cat:

Class 2 for cats
package Inheritence;

public class cat {

	
		
	

}
Class 1 for dogs
package Inheritence;

public class dog {

	
		
	

}

 

and add for both classes the extends keyword. In this you let the classes inherit (that is why it is called inheritance) the characteristics of the class it extends. Resulting in this:

Class 1 for dogs
package Inheritence;

public class dog extends blackPets{

}
Class 2 for cats
package Inheritence;

public class cat extends blackPets{

}

The method: start, in the main class (pets) will work exactly the same. In this, it will safe time. In the case of a bigger class, inheritance will optimise your code in a way of shorter code and it will be better readable because everything is in its own class.

 

Advantage