0

In java we are not able to create an instance of an interface like this:

iJack obj = new iJack();    //iJack is an interface

However, I noticed that we can do this:

iJack obj;

What is the difference between the two?

In addition to that, I noticed that you can nest a class within an interface, how is this useful? I can not think of a practical purpose for this. Here is an example of what I am talking about:

public interface iJack {
    public abstract class Jack_class {

    }
}
admdrew
  • 3,790
  • 4
  • 27
  • 39
user3240944
  • 331
  • 1
  • 2
  • 8
  • Please use the correct Java naming conventions for classes/interfaces (start with capital letter, no underscore, just use CamelCase). – u3l Feb 19 '14 at 15:10
  • why this post is tagged to Android?? – Med Besbes Feb 19 '14 at 15:13
  • Do you have a C/C++ background? Java has only references to objects, it never declares and object on the stack. `iJack obj;` declares an uninitialized reference `obj`, it does *not* instantiate an instance of `iJack` on the stack. – Erwin Bolwidt Feb 19 '14 at 15:13
  • Nesting a class in an interface is just a lexical scope thing. It's useful if the class has a close association with the methods in the interface. It's basically the same as a `public static` nested class inside another class. – Erwin Bolwidt Feb 19 '14 at 15:19
  • You should start by reading this: http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html – StephaneM Feb 19 '14 at 15:20

2 Answers2

0

Interfaces can not be instantiated. Only classes can. However, you can (and should) use an interface as the type of a variable.

Your line...

iJack obj;

...declares a variable of the iJack type, but it does not initialize it.

By the way, you should always use a capital letter at the beginning of an interface name.

Andres
  • 10,561
  • 4
  • 45
  • 63
0

If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

you asking what is the difference between the two. first one is wrong. you can't instantiate interface but classes that implement those interfaces. so you can't talk about differences

Reference :Using an Interface as a Type

the uses of nested classes in interface has the same purpose as the uses of nested classes in another class. that is scoping the class to the interface.

Reference :Nested class inside an interface

Community
  • 1
  • 1
lakshman
  • 2,641
  • 6
  • 37
  • 63