Inheritance in Java Example

Inheritance is one of the basic concepts of Object Oriented Programming. Java supports inheritance and define an is-a relationship between a superclass and a subclass. For example if Vehicle is the superclass and Car is the subclass inherited from superclass Vehicle, then Car is-a Vehicle too.

Inheritance in Java is the method to create a new class from an existing class. Inheritance in java is transitive, so if Sedan extends class Car, then Sedan is also inherited from Vehicle class. Vehicle becomes the superclass of both Car and Sedan.

Inheritance is widely used in java applications, for example extending Exception class to create an application specific Exception class that contains more information like error codes.

In java, every class implicitly extends java.lang.Object class, so Object class is at the top level of inheritance hierarchy in java.

Let’s see how we implement inheritance in java with simple example:

package com.journaldev.inheritance;

public class Animal {

	private boolean vegetarian;

	private String eats;

	private int noOfLegs;

	public Animal(){}

	public Animal(boolean veg, String food, int legs){
		this.vegetarian = veg;
		this.eats = food;
		this.noOfLegs = legs;
	}

	public boolean isVegetarian() {
		return vegetarian;
	}

	public void setVegetarian(boolean vegetarian) {
		this.vegetarian = vegetarian;
	}

	public String getEats() {
		return eats;
	}

	public void setEats(String eats) {
		this.eats = eats;
	}

	public int getNoOfLegs() {
		return noOfLegs;
	}

	public void setNoOfLegs(int noOfLegs) {
		this.noOfLegs = noOfLegs;
	}

}

Animal is the base class here, now lets create a class Cat which inherits from Animal class.

package com.journaldev.inheritance;

public class Cat extends Animal{

	private String color;

	public Cat(boolean veg, String food, int legs) {
		super(veg, food, legs);
		this.color="White";
	}

	public Cat(boolean veg, String food, int legs,String color){
		super(veg, food, legs);
		this.color=color;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

}

extends is the java keyword used to implement inheritance in java.

Now let’s write a simple test class to create Cat object and use some of it’s methods.

package com.journaldev.inheritance;

public class AnimalInheritanceTest {

	public static void main(String[] args) {
		Cat cat = new Cat(false, "milk", 4, "black");

		System.out.println("Cat is vegetaring?" + cat.isVegetarian());
		System.out.println("Cat eats " + cat.getEats());
		System.out.println("Cat has " + cat.getNoOfLegs() + " legs.");
		System.out.println("Cat color is " + cat.getColor());
	}

}

Output of the above program is:

Cat is vegetaring?false
Cat eats milk
Cat has 4 legs.
Cat color is black

As you can see that Cat class doesn’t have getEats() method but still it works because it’s inherited from Animal class.

Important Points for Inheritance in Java

  • Private members of superclass are not directly accessible to subclass. As in this example, Animal variable noOfLegs is not accessible to Cat class but it can be indirectly accessible via getter and setter methods.
  • Subclass members with default access is accessible to subclass ONLY if they are in same package.
  • Superclass constructors are not inherited by subclass.
  • If superclass doesn’t have default constructor, then subclass also needs to have an explicit constructor defined. Else it will throw compile time exception.
  • Java doesn’t support multiple inheritance, a subclass can extends only one class. So here Animal is implicitly extending Object class and Cat is extending Animal class but due to java inheritance transitive nature, Cat class also extends Object class.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Today's Special: Java Persistence API PDF eBook Free Download Now
Exclusive Offer: Citrix™ Whitepaper on Denial of Service Attack Download Now