1

Assume that there is a base class without any method or attribute, like below class Base.

public abstract class Base {
    public Base() {}
}

And we have another class(es) derived from class Base, say class Concrete. As far as I know, when we create an instance of the Concrete class, two instances are created: First one is class Base and second one is class Concrete. Consider the following code, 200 instances are created.

for(int i = 0; i < 100; i++)
    Concrete c = new Concrete(); 

For the above situation, is that meaningful to make class Base an interface? If we do so, how many instances will be created, 100 or 200? In other words, are interfaces common for all class instances or each class instance has its own interface instance?

2
  • 1
    i don't think two instances are created. only constructor is getting called. Commented Mar 6, 2015 at 9:40
  • 1
    100 object is created and every object pass both the is-a Base and is-a Concrete tests. (It will be both Base and Concrete and Object in the same time.) Commented Mar 6, 2015 at 9:43

2 Answers 2

4

If you create instance for derived class no separate instance will be created for abstract class. only default constructor will get called to initialize the class (here it means that it will assign default values for the fields).

if you check instanceof operator for both class on same object you will get true response.

if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.

If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.

Sign up to request clarification or add additional context in comments.

Comments

3

Since your abstract base class doesn't have any functionality, it would be more useful as an interface.

In either case, only 100 instances are created (of class Concrete). Those instances just happen to be also instances of Base.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.