abstract class with default constructor and class with private constructor difference

1.3k views Asked by At

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();
}
}
2

There are 2 answers

0
Jon Skeet On BEST ANSWER

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.

0
bpgergo On

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...