Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If interfaces do not have constructors, then is Object class super class of an interface?

I read that interfaces do not have a constructors, which means it will not call super() of its super class. I also read that each and every class in Java is a subclass of Object

What about an interface, is it subclass of Object? Why?

like image 253
dhiral pandya Avatar asked May 18 '12 06:05

dhiral pandya


3 Answers

No it's not. An interface cannot be instantiated to form an object, it is not a class.

like image 77
David M Avatar answered Sep 22 '22 19:09

David M


An interface is a named collection of method definitions (without implementations). An interface can also include constant declarations.

Interface and class have some basic difference and one of them is do not have a constructors. Actually interface does not made for it and you cannot instantiate interface but there is way you can still instantiate interface.

interface Interface{
     abstract String fun();
 }

Interface interfc=new Interface() {
    @Override
    public String fun() {
        return super.toString();
    }
};

Type type=interfc.getClass();

Here interface has been instantiated as anonymous class.But still you cannot place constructor here according to java language specification. But still you can use super class Which will be immediately super class of this anonymous class.

An anonymous class cannot have an explicitly declared constructor.

And there is alternative solution of this that is using final variable in super class.

like image 23
Subhrajyoti Majumder Avatar answered Sep 22 '22 19:09

Subhrajyoti Majumder


No interface is a subclass of Object class, since interface cannot extend a class whether implicit or explicit.

Reason for constructor is to create an instance, since interface cannot be instantiated as they don't provide any functionality they are just a contract only class can be instantiated hence they have constructor.

like image 35
mprabhat Avatar answered Sep 24 '22 19:09

mprabhat