0

If I define a class as

class A {
    interface AL {
        void method ();
    }
}

Then why doesn't the compiler ask me to mark the class as abstract since I have an undefined method in it?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

3 Answers3

1

Since method() is a method of the interface AL, the code works fine. Note that method() is not a method of A, and, therefore, there is no need for the class A to be abstract.

Gabriel Ilharco
  • 1,649
  • 1
  • 21
  • 34
0

The method without its implementation is a part of the nested interface declaration. It is not considered a part of the outer class. You might want to take a look at why it is a good idea to have nested interface declarations.

Why should we declare an interface inside a class?

Community
  • 1
  • 1
alpha_ulrich
  • 536
  • 5
  • 21
0

Consider an example :

Suppose you are creating some application which is concerned with the animal kingdom.

Now you are asked to create a dog, cat, lion etc objects.

So first thing will come to your mind, since these all belong to animal kingdom I can create a base class named ' Animal ', and everything will inherits it. Now yo created something like this

class Animal {    
legs;    
family; 

eat();    
roam();  
sleep();     
makeNoise();    
}

So all the animals inheriting the animal class will have these features. You can call this as a "IS-A" relationship. Like Dog IS-A Animal.

Now suppose you are asked to use your animal simulation program for some science-fair. You can use this design in that too.

Now suppose someone asked you to use your simulator in a pet-shop.

Since you don't have any pet behavior. What you did is add the pet features in the base class and thought this will work.

So now you program can create a lion which has the pet behavior. STRANGE!!

Now what you need to put all the pet behavior in one place and make sure that all the pet animals should posses it.

A way to do is create another superclass with all pet features and extend it. This is multiple inheritance, which JAVA don't allow (just Google deadly diamond of death). So comes the interface.

Interface is more like a set of behaviors which your object implements. And since every object can have its own set of implementations, all these methods should be abstract.
It gives you polymorphic benefits without deadly diamond of death problem. It is a more like a contract which defines that your object must implements following features.

So now what you can do

interface PetBehavior{    
  befriend();    
  play();    
}  

and classes from different inheritance tree can implement this interface.

Abstract class gives you a brief idea how a concrete object will may look like but an interface is more like a contract. It tells you what additional features will object will have.

mykpc
  • 37
  • 1