Interface and Inheritance in Java: Inheritance

Sandeep Panda
Tweet
This entry is part 2 of 2 in the series Interface and Inheritance In Java

Interface and Inheritance In Java

 
When a class extends another class it’s called inheritance. The class that extends is called sub class while the class that is extended is called super class. Any class in java that does not extend any other class implicitly extends Object class.

In other words every class in java directly or indirectly inherits Object class.

By means of inheritance a class gets all the public, protected properties and methods of the super class no matter which package the sub class is present in. If the sub class is present in the same package as that of super class then it gets the package private properties and methods too. Once the sub class inherits the properties and methods of super class, it can treat them as if it defined them.

By using inheritance you can reuse existing code. If you have an already written class (but no source) and it lacks some features then you don’t have to write everything from scratch. Just extend the class and add a new method that satisfies your needs.

Note:

Private methods and properties are not inherited. However, if the super class has a private variable and a public method that uses the variable then the variable is made available inside the method in the sub class. You should also note that constructors are never inherited.

How to Extend

Use extends keyword to inherit the super class-

class A{

//properties and methods of A

}

class B extends A {

}

Note: A class can inherit only one class. Multiple inheritance is not supported in Java.

Method Overriding And Hiding

When a sub class defines a method that has same signature and return type (or compatible with return type of super class method) it is called method overriding.

Example:

class A{

int x;

public void printIt(){

System.out.println(“method in class A”);

}

}

class B extends A{

public void printIt(){

System.out.println(“method in class B”);

}

}

class Test{

public static void main(String[] args){

A a=new B();

a.printIt(); // prints “method in class B” without quotes

}

}

Here class B extends class A and overrides the method printIt(). So, when we run the above code the method that gets called is printIt() of class B. By overriding printIt() defined in class A, class B can provide a different implementation to it. Still it can access the super class version of the method by using super keyword.

Example:

class B extends A{

public void printIt(){

super.printIt();

System.out.println(“method in class B”);

}

}

Note:

In the previous example we have used the reference of type A and object of B. But whose printIt() method will be called is not decided during compilation time. Java waits till the runtime of the program and checks which object the reference is pointing to. In this case the object is of class B. So, it’s B’s printIt() method which is getting executed. This is called dynamic method dispatch or virtual method invocation.

Now let’s assume class A has a static method printStatic  and class B, which is a sub class of A, defines a static method having same signature as that of A’s printStatic. This is a case of method hiding.

Example:

class A{

public static void printStatic(){

System.out.println("In A");

}}

class B extends A{

public static void printStatic(){

System.out.println("In B");

}

}

class Test{

public static void main(String[] args){

A a=new B();

a.printStatic(); // prints “In A” without quotes

//We can also call like this A.printStatic()

}

}

In this case at compilation time Java will look for the reference type and not the object that is being pointed to. Here, the reference type is A. So, printStatic() of class A is executed.

Casting Objects

Let’s take the example where class A is super class and class B is the sub class. We already know that it is possible to create an object of class B and assign it to a reference of type A. But by doing this you will be able to call the methods that are defined in class A only. In order to call the methods that are defined by class B you need to cast the reference.

Example:

A a=new B();

a.methodSpecificToB(); // illegal

B b=(B)a;

b.methodSpecificToB(); //legal

Constructor Chaining

When we instantiate a sub class the super class constructor also runs. It happens by means of a call to super(). When we don’t explicitly call super() inside a sub class constructor the compiler implicitly puts super() as the first statement in each of the overloaded constructors (like methods, constructors can also be overloaded) assuming that a call to this() is not present in the constructors.

If you don’t define a constructor for your class the compiler creates a default constructor (which is no arg) and places a call to super(). The only condition is that your super class should have a no arg constructor or else it will produce a compile time error. If you have a super class that does not have a no arg constructor then you should call super() with appropriate parameters from your sub class constructor.

The concept will be clear from the following example:

class A{

A(){

System.out.println(“Constructor of A running”);

}

}

class B extends A{

B(){

//a call to super() is placed here

System.out.println(“Constructor of B running”);

}

}

public class Test{

public static void main(String[] args){

new B();

}

}

Output

Constructor of A running

Constructor of B running

Note: The sub class constructor is called first, but it’s the super class constructor that finishes executing first.

Summary

  • A class can extend only one class.
  • Every class is a sub class of Object directly or indirectly.
  • A super class reference can refer to a sub class object.
  • If reference is super class and object is of sub class then calling an instance method on it will result in execution of the method defined in sub class.
  • An overridden method has same signature and return type (or compatible with the return type) as that of super class method.
  • We can hide a static method defined in super class by defining a static method having same signature or return type (or compatible with the return type) as that of super class method.
  • When a sub class constructor runs the super class constructor also runs. This is called constructor chaining.

Interface and Inheritance In Java

<< Interface and Inheritance in Java: Interface

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Alice Young

    Besides being very dry and boring, you make a number of completely wrong statements. “if the super class has a private variable and a public method that uses the variable then the variable is made available inside the method in the sub class.” NO. Won’t even compile.
    “We can hide a static method defined in super class by defining a static method having same signature or return type (or compatible with the return type) as that of super class method” NO. You can’t override static methods.
    “But by doing this you will be able to call the methods that are defined in class A only.” NO AGAIN. It’s still an instance of class B, regardless of what you cast it to.
    Your examples are also wrong and show that you don’t really understand what is going on with inheritance.

    • http://gadgeticworld.com/ Sandeep Panda

      Hi Alice,

      Do you even have any idea about what you are trying to say? You wrote several points, but did you try to compile and run any code to prove your points?

      1. If there are any public methods in super class that access private variables, these can also be used inside subclass. Check out Oracle’s documentation: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html . Open up the page and go to “Private members in a super class section”. Yes, the code will compile. Try it out yourself.
      2. My dear friend, I am not talking about overriding static methods. As you have quoted my lines it’s clearly written that if you define a static method in sub class that has same name and signature as the static method in super class it hides the method (not overrides). The code will compile and run just fine. Again check out Oracle’s docs: http://docs.oracle.com/javase/tutorial/java/IandI/override.html (Go to Summary section in the end).
      3. Looks like you don’t have basics of Inheritance. If A is super class and B is its sub class and you create an object of B, assign it to reference of type A then you can call those methods that are defined in A (If B overrides these methods then B’s version of the methods will be called). If you try to call methods specific to B then compiler will surely generate error. If you really want to call the methods that are defined in B you have to cast the reference. I strongly suggest you to go through Oracle docs on Java basics. Please check out this StackOverflow question: http://stackoverflow.com/questions/5306835/casting-objects-in-java

      Alice,before pointing out anything please open up your editor, write a test code and run it.

      Thanks for the read.

      Regards,
      Sandeep

  • Richard Hassinger

    Sandeep,
    I understand you love Java but you need to learn it thoroughly first before trying to write about it to the masses. (Granted, most readers of sitepoint probably stick to the softer scripting languages, but still, the web doesn’t need more misinformation.) Don’t just try to paraphrase a textbook. Alice is correct in her points. 1) private vars are not available to the subclass. This would have to be protected scope. 2) Static methods belong to the class, not the object. You don’t subclass static. 3) You just posted another article about polymorphism. Assuming you actually understand what you wrote, you would know that your statement was wrong. If you call a method on A which was overridden in B, you would get B’s functionality, not A’s. The way you (mis)wrote it, you infer that you magically changed B into an A, and that’s simply not true.
    Kind regards,
    Richard

    • http://gadgeticworld.com/ Sandeep Panda

      Hi Richard,

      Thanks for commenting. I am sure my article does not contain any misinformation. I think you misinterpreted my statements. Just think about this: A super class has a private variable and also has a public getter method that returns value of the private property. Suppose now you subclass the super class. Obviously the private variable won’t be available to the sub class. But what happens when you try to call the inherited public method of the subclass object? In this case the private variable of super class is made available inside the inherited public method of sub class. This is applicable for both protected and private properties. In my previous comment I gave a link to Oracle’s docs that clearly explains the fact.

      I don’t really get the meaning of your statement “You don’t subclass static”. There is absolutely no confusion that static methods belong to classes and not the objects. But you can hide a static method(I never really talked about overriding static methods which is not possible) in sub class simply by defining a static method with same name and signature. This is called hiding static methods which is perfectly legal in Java.

      Addressing your last query, I would say that you again missed my point. Suppose you have super class reference and sub class object. If you call an overridden method on super class reference no doubt you will get sub class’s functionality. But in addition to the inherited methods, sub class can also define some methods of its own(super class has no idea about these methods ). What will happen if you try to call these methods on super class reference? Compiler will generate error for sure!So, you need to cast the super class reference to sub class type. Then you can call the methods defined in subclass.

      I am sure, this will clear all the confusions. I am also giving a quick example here which will clearly explain these concepts. I was wondering if you checked out the link to Oracle documentation that I provided in my previous comment to Alice? I am pretty sure what I am writing here is in accordance with the docs.

      Let me know what you think, Richard!

      Example Code:

      public class Test{
      public static void main(String[] args){
      B b=new B();
      System.out.println(b.getA()); //prints 10 -->private variable of super class
      // made available inside inherited sub class method.
      A a=new B();
      a.print(); //Compile time error!! A has no idea about print() in B
      ((B)a).print(); // it works now by casting!
      }
      }
      class A{
      private int a=10;
      public int getA(){
      return a;
      }
      public static void printStatic(){
      System.out.println("In A");
      }
      }
      class B extends A{
      public void print(){
      System.out.println("In B");
      }
      public static void printStatic(){ //This method hides super class static method
      System.out.println("Belongs to class B");
      }
      }

      Regards,
      Sandeep

  • Steve

    Sandeep has written a very lucid and apt article.. It won’t be out of contect to mention that folks need easy to understand article, not some full blown crap.

    Alice and Richard: My advice for guys would be to first write a single line of Java code. Then you can try blabbering.