Search code examples
javasubtype

(Java) Difference ways of instantiating subclasses


I have these two classes:

public class A {}
public class B extends A {}

In the main class, I would declare:

A a = new B();
B b = new B();

What is the difference between a and b ? Is this what we called a subtyping in java?


Solution

  • The difference between a and b is that with a you can only use the public API that the A class provides even though its really a B type object, but with b, you can use both the A's public API as well as B's public API.

    For example:

    Suppose A and B are defined as follows:

    // A.java
    public class A
    {
      public void x()
      {
        z("X");
      }
    
      public void y()
      {
        z("Y");
      }
    
      protected void z(String message)
      {
        System.out.println(message);
      }
    }
    
    // B.java
    public class B extends A
    {
      public void a()
      {
        z("A");
      }
    
      public void b()
      {
        z("B");
      }
    }
    

    And here's a demo:

    // Demo.java
    public class Demo
    {
      public static void main(String[] args)
      {
        A a = new B();
        B b = new B();
    
        // Can only call A's public methods
        a.x();
        a.y();
        // a.a(); Can't use
        // a.b(); Can't use
    
        // Can call all public methods
        b.a();
        b.b();
        b.x();
        b.y();
      }
    }