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 {
}
}
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.
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
Related
I am creating an interface with many implementing classes and there is an attribute they must all have;
I guess it's better to put that attribute in their interface than writing many constructor lines, but attributes can only be static final and require to be immediately initialized.
public interface Interface{
static final AttrType attribute = new AttrType( *something* );
I have 2 problems: this attribute is a class and its constructor needs some other type parameters not just ints, and also it shouldn't be initialized here, I need all implementing classes of the interface to work on the same instance of AttrType which as i said I won't instantiate in the interface.
So, as I am not expert enough, is there a way to do this in the interface or I should just write a line in every subclass' constructor to put in the one AttrType instance they need?
Java interfaces describe what a class can do, rather than what a class is. Therefore, an interface only describes methods.
You could handle this in a few ways:
Using an interface, you could have a getter for the variable, which would force the implementing classes to have the variable. Something like "public AttrType getAttribute();"
Or you could create a class, probably abstract, which implements the interface and has the variable, and its getter and setter. The subclasses all would inherit this variable and behavior.
Would it be possible to add also a common base class to go with your common interface which all the classes could inherit? Then the common base class constructor could contain the attribute instance. Also you could consider using an abstract class instead of interface.
I'm dealing with a contractor's code. For whatever reason he has made a series of "constants" files that are all interfaces. They look like this:
interface SomeTypeConsts {
public static class SomeSubTypeA {
public static final String CONSTANT_A = "foo";
public static final String CONSTANT_B = "bar";
}
public static class SomeSubTypeB {
public static final String CONSTANT_A = "baz";
}
}
and so forth. There are no unimplemented/abstract methods, the files just contain nested classes some arbitrary level deep, and static final Strings for the constants. I cannot modify the contractor's code at this time.
I'm writing a test framework and I need an instance of one of these constants interfaces. All of them follow the above pattern, but my method needs to support all of them and not just one in specific.
I tried instantiating the interface using Reflection like this:
clazz.newInstance() // where clazz is Class<SomeTypeConsts>
But it threw a java.lang.InstantiationException.
All of the questions here on SO say that you need to implement the interface first, then use that instance. And if I knew ahead of time which const interface it was, I could easily do SomeTypeConsts consts = new SomeTypeConsts(){};. But I haven't been able to figure out how to do this with reflection, when all I have to work with is the Class<SomeTypeConst>.
Given an interface Class reference, with no abstract methods to be overwritten/implemented, how can I instantiate an instance of it using reflection?
You could do this using a JDK proxy for the interface, but it would be entirely pointless: If all you're doing is accessing static members, all of that is resolved without reference to any actual instance of the type in question, either at compile-time (far preferable) or at runtime with some approach like enumerating the fields and filtering on the static ones.
From the language spec (emphasis mine):
This type has no instance variables, and typically declares one or more abstract methods; otherwise unrelated classes can implement the interface by providing implementations for its abstract methods. Interfaces may not be directly instantiated.
And, from the Javadoc of Class.newInstance():
[throws] InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.
You can't instantiate an interface. You can only instantiate (non-abstract) classes which implement it.
No. You cannot do that. Interfaces by definition are not instantiable.
What you need is a mock object. Not reflection
The title is not quite clear, but I didn't see how to explain it in a short sentence.
I have an interface myInterface (This must be an interface, not an abstract, because enum will implement it).
I expect to have an attribute myAttribute (integer) which is not reachable from outside, except for the derivated classes from the interface (protected).
I want a method myMethod that contans myInterface as input parameter. But then, I have trouble when I try to implement it.
The method looks like this
boolean myMethod(myInterface interface)
{
return this.myAttribute>interface.myAttribute;
}
I can't define "myAttribute" as protected in "myInterface".
If I don't define "myAttribute" in "myInterface", I can't use it in the definition of myMethod, when I implement it in my derivated class : The signature should contain "myInterface" as input parameter, and this one doesn't have any "myAttribute" attribute.
The only solution I have now is to cast "myInterface" in its derivate, but I don't like it (Globally, I don't like casts). Does anyone has another idea?
You cannot.
Interfaces can only define (implicitly) public static final variables, otherwise said, public constants.
What you should do is define a method returning your attribute in your interface, which in turn, its implementing classes will be forced to implement (if they're not abstract).
The method will be implicitly public.
This will also enforce the encapsulation of the variable within the implementing classes.
You can then retrieve the value by virtually invoking the getter method on the interface: myInterface.getMyAttribute().
Edit
If your scope is to not be able to access the value an instance field outside classes that implement a common interface at all, you can proxy you hierarchy by having an abstract class in between the interface and your implementing classes.
In turn, the abstract class would implement none of the interface methods (hence still forcing the concrete classes to implement all), but instead feature a protected attribute that the concrete classes would all have access to.
Finally the concrete classes could decide whether or not to let other classes access that field.
I am preparing for an OCJP. I came across this statement in Kathy Sierra's book.
Interfaces are not part of Object hierarchy in Java
I am just curious and want to know why ?
In order to precise things a bit:
An interface is not part of the object hierarchy, meaning that an interface which does not extend another one has no supertype.
However, an instance typed as an interface is always an Object, otherwise you would not be able to write things like:
interface MyInterface { //no supertype.
}
MyInterface var = new MyInterface(){};
var.toString(); //toString method is defined on Object class.
as you know an interface can not inherits from any class, so it can not be inherited directly or indirectly from Object class, that's why an interface does not belongs to Object hierarchy like other classes for example String,etc
I'm reading Head First Design Patterns and have some understanding in Java. It starts by encapsulating things that vary from your class and putting them in a seperate interface, as opposed to putting those functionality in the subclass. The example they give is an abstract Duck class that can quack or fly depending on the duck. They have an interface for quack and fly (QuackBehavior and FlyBehavior interfaces), and then implement those interfaces in other classes.
In the example, they have the abstract duck class as follows
public abstract class Duck {
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;
.....
}
I guess what is new to me is having an instance variable that is of the interface type. I never learned that before but I'm assuming it's valid? I guess I'm more familiar with having an instance variable of a concrete class. Are there any rules about having instance variables of classes/interfaces like this? Thanks.
It is valid, and a common practice.
It doesn't matter what the instance variable is. It is even preferred to use interfaces where possible. For example always define variables of type List and not ArrayList
Otherwise how would you be able to have different behaviours? Now you can assign both LowFlyBehaviour and HighFlyBehaviour to the field, and thus different instance of Duck can have different flying behaviours. If the field was either of these concrete types, this would not be possible.
Yes, it's valid. The only rules the apply are the same the apply for any other type; namely that you can only assign something that implements the declared interface. You have probably seen or even used a similar syntax before without realizing it, like:
List<String> list = new ArrayList<String>();
Serializable s = new Object();
If you declare a field as an interface type, the filed will be able to hold any class that implements the interface.
It's a normal field.