Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
}
like image 494
Vaibhav_Sharma Avatar asked Jun 01 '26 11:06

Vaibhav_Sharma


1 Answers

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.

like image 143
Tim Biegeleisen Avatar answered Jun 03 '26 01:06

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!