The principle of the solution: abstract class can actually be instantiated, but his instantiation is not through the new way to create the object, but through the parent class reference to point to the child class instance to indirectly implement the parent class instantiation (because before the subclass is instantiated, it is bound to instantiate his parent class first.) This creates an object that inherits the subclass of the abstract class, and then instantiates its parent class (the abstract Class).
But:interfaces cannot be instantiated (interfaces have no constructors at all), similar to the principle above, the reference to the same interface type can point to the object of its child class
Example: Package com.etc;
Public abstract class A
{
Privatestring str;
PublicA (String a)
{
System.out.println ("Parent class has been instantiated");
This.str=a;
System.out.println (str);
}
publicabstract void Play ();
}
Package com.etc;
public class B extends A
{
PUBLICB (String a)
{Super (a);
System.out.println ("Subclass has been instantiated");
}
Public Voidplay ()
{
System.out.println ("I have achieved the method");
}
publicstatic void Main (string[] args)
{
A AA = newb ("AA");
}
}
The result of running Class B is as follows: The parent class has been instantiated
Aa
Subclasses have been instantiated
Other than that:
GetInstance () in the calendar
Calendar cal= calendar.getinstance ();
The calendar is an abstract class that cannot be passed directly through the new object, but the provided static getinstance () is the object created for the calendar.
The instance obtained from Calendar.getinstance () is actually a "Greogriancalendar" object
Greogriancalendar is the child of the calendar, and he implements the abstract method in the calendar.a reference to the parent class to point to an instance of the subclass to indirectly implement the instantiation of the parent class. At the same time, using getinstance () has many benefits:
1. New must be generated to allocate memory; getinstance () does not have to be created again, it can use an existing reference to you, which is better than new in performance;
2. New can only be used once when it is created, and getinstance () can be used across the stack area or remotely across regions. So getinstance () is usually created by static instance methods.
Can abstract methods really not be instantiated?