简体   繁体   中英

Since an abstract class can have a public constructor, why can't we instantiate it?

I know a singleton class cannot be instantiated because it has a private constructor. I would assume the same for an abstract class, but it can contain an public constructor, so why can we not instantiate an abstract class?

I have constructed a small example to answer 2 questions

1. Why one might need a public constructor inside an abstract class?

Assume you have an abstract class Animal which is inherited by classes Dog & Monkey (We can add many child classes like this)

abstract class Animal {
    int legs;

    public Animal(int legs) {
        this.legs = legs;
    }
}

class Dog extends Animal {
    public Dog(int legs) {
        super(legs);
    }
}
class Monkey extends Animal {
    public Monkey(int legs){
        super(legs); 
    }
}

Now if we create a Dog object and call its constructor it will in return call the constructor of Animal class and update int legs . If you observe we can now use the constructor of Animal class and use it to update the value of an N number of classes which inherit it. So one might use a public constructor inside an abstract class.

2. Why can't we instantiate the object of an abstract class? source

You cannot create an instance of an abstract class because it does not have a complete implementation. The purpose of an abstract class is to function as a base for subclasses. It acts like a template, or an empty or partially empty structure, you should extend it and build on it before you can use it.

Here is a little modification to our example

abstract class Animal {
    int legs;
    String ability;

    public Animal(int legs) {
        this.legs = legs;
    }

    abstract void showAbility();
}

class Dog extends Animal {
    public Dog(int legs) {
        super(legs);
    }
    public void showAbility() {
        System.out.println("Sniff");
    }
}
class Monkey extends Animal {
    public Monkey(int legs){
        super(legs); 
    }
    public void showAbility() {
        System.out.println("Climb");
    }
}

Now assume if you were able to create an object like new Animal() then will new Animal().showAbility() had a meaning? No. because it does not have a complete implementation. I believe this is a good reason why objects of abstract classes can't be instantiated.

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