Vaibhav_Sharma
Vaibhav_Sharma

Reputation: 546

Q: Abstract class object initiation code?

In this class abstract class object is instantiated by overriding the getNum(), what is the purpose of this?

public abstract class AbstractTest {
 public int getNum() {
  return 45;
 }
 public static void main(String[] args) // main function
  {
   AbstractTest t = new AbstractTest() // From this point didn't understand
    {
     public int getNum() // function
      {
       return 22;
      }
    }; //use of this        
   System.out.println(t.getNum()); // output
  }
}

Upvotes: 3

Views: 102

Answers (2)

magooup
magooup

Reputation: 134

We call this 'Anonymous Class': When you need to create and use a class, but do not need to give its name or reused use, you can use an anonymous class. Here is the offical doc. Not only used for abstract class, can also be used for interface and general extensible class.

interface Base {
    void print();
}
public static void main(String[] args) {

    Base aInterface = new Base() {
        @Override
        public void print() {
            System.out.println("A anonymous implement.");
        }
    };

    Thread aThread = new Thread() {
        @Override
        public void run() {
            super.run();
        }
    };
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

The instantiation in your main() method is simply an inline class definition of a concrete instance of the abstract class AbstractTest. To be clear, the variable t is an anonymous, non abstract class instance. The following code would achieve the same thing:

public class ConcreteTest extends AbstractTest {
    @Override
    public int getNum() {
        return 22;
    }
}

public static void main (String [] args) {
    ConcreteTest t = new ConcreteTest();
    System.out.println(t.getNum());
}

There are instances in the course of development where it can be cumbersome to have to create a formal class definition. For example, if you only need a single instance of the abstract AbstractTest class, it would be easier to use an inline definition.

Upvotes: 3

Related Questions