简体   繁体   中英

abstract class with default constructor and class with private constructor difference

what's the difference between an Abstract class with a default constructor and a class with private constructor?

I also have another doubt , consider this program below. Can anyone please explain me.Does such code have any use ?

abstract class AbstractAndPrivate 
{
AbstractAndPrivate()
{
     AbstractAndPrivate ref= new AbstractAndPrivate(1) {

        @Override
        int m2() {
        // TODO Auto-generated method stub
        return 0;
        }
                    };  

            }
void m1()
{
    System.out.println("m1() accessed");
}
abstract int m2();

AbstractAndPrivate(int a)
{

}
public static void main(String[] args) {

System.out.print("hello ");

 AbstractAndPrivate ref= new AbstractAndPrivate() {public int m2(){return 1;}}; 
 System.out.println(ref);
 ref.m1();
 ref.m2();
}
}

what's the difference between an Abstract class with a default constructor and a class with private constructor?

If there's a default constructor, it will be callable from subclasses. If it's private , you'll only be able to create subclasses within the same class, as that's the only context in which the private constructor will be accessible.

Note that the code you've provided is neither of these situations - it's explicitly providing a package-protected parameterless constructor. That's not private, and it's not a default constructor.

Whether the class is abstract or not is orthogonal to the constructors it provides, although an abstract class with only a private constructor forces you to create subclasses within the declaring class in order to create instances, rather than just relying on you creating instances within the declaring class.

also, abstract class can have an abstract method , that needs to be implemented by subclasses (unless they're abstract too)

EDIT : -1? come on, abstract methods are also sort of explains the logical difference between abstract classes and classes with private constructor. please...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM