This question already has answers here:
Inner class within Interface
(13 answers)
Closed 7 years ago.
In which scenario can an interface have nested classes?
The following code is allowed and valid.
public interface Iface {
void show();
class ifaceClass {
int x;
public ifaceClass() {
System.out.println(x);
}
}
}
I am also struggling to make object of class ifaceClass.
EDIT :
I am able to make object like this
public class Test implements Iface {
public static void main(String[] args){
ifaceClass ifaceClassObj = new ifaceClass();
}
public void show() {
}
}
I noticed if Test has not implemented the Iface then I needed following import,
import com.jls.Iface.ifaceClass;
But it boiled down to same problem that why not use it as a just another class.
What the difference or value addition with this approach ?
You can create an instance of ifaceClass inside the class that implements Iface:
interface Iface {
void show();
class ifaceClass {
int x;
public ifaceClass() {
System.out.println(x);
}
}
}
public class Test implements Iface {
public static void main(String args[]) {
ifaceClass iface = new ifaceClass();
}
#Override
public void show() {
// ...
}
}
If the class doesn't implement the interface, just create an instance like this:
Iface.ifaceClass iface = new Iface.ifaceClass();
Why create a class inside an interface? Basically for the same reason you create a class inside another class, to group related classes together.
Where it is useful to have nested classes in an interface?
There is no such case which can only be fulfilled with inner class of interface. It is syntactically valid to have inner class in interface and for the class which implement interface can create instance of class and apart from that Interface.Class can also make that class accessible because it can not be private at all.
I noticed if Test has not implemented the Iface then I needed
following import import com.jls.Iface.ifaceClass;
Not necessarily, if your interface is accessible your inner class will automatically become accessible.Here you are trying to access class directly without even importing interface in that case following statement need above import statement.
ifaceClass ifaceClassObj = new ifaceClass();
But it boiled down to same problem that why not use it as a just
another class. What the difference or value addition with this
approach
Exactly, creating another class can also provide you the same facility and I have never seen any use case in my day to day programming which can only be fulfilled with inner class of interface.It does not provide anything else than accessibility through the interface.
I have used it once which I think quite a bad practice though. One day we need to implement one common method in different classes which are implementing interface say X and we wanted to add one extra method to be used by all this classes to add one kind of check on the Object which only check some parameter and return boolean even though that use case can be fulfilled in other way but to be specific that it is only intended for classes which are implementing this interface we have added class in interface so that we can provide that method to implementing classes.(NOTE : Nowadays default method can be used in this case instead of inner class)
Here, it is wise to note that in huge projects it is quite impossible for anyone ( other than creator ) to note that any interface has inner class. So, until we implement that class or manually check the interface we can not came to know that interface has inner class.
Related
This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc
This question already has answers here:
What is a static interface in java?
(3 answers)
Closed 3 years ago.
Below class is a java class where i have seen static interface Inside this class what is the use of this static interface i have never seen and what advantages to create interface like this
public class Validator {
public static interface ItemValidator {
public int withinTolerance(Number value, Number oldValue);
}
}
An interface which is declared inside another interface or class is called nested interface. They are also known as inner interface. Since nested interface cannot be accessed directly, the main purpose of using them is to resolve the namespace by grouping related interfaces (or related interface and class) together. This way, we can only call the nested interface by using outer class or outer interface name followed by dot( . ), followed by the interface name.
Example: Entry interface inside Map interface is nested. Thus we access it by calling Map.Entry.
Note:
Nested interfaces are static by default. You don’t have to mark them static explicitly as it would be redundant.
Nested interfaces declared inside class can take any access modifier, however nested interface declared inside interface is public implicitly.
Example 1: Nested interface declared inside another interface
interface MyInterfaceA{
void display();
interface MyInterfaceB{
void myMethod();
}
}
class NestedInterfaceDemo1
implements MyInterfaceA.MyInterfaceB{
public void myMethod(){
System.out.println("Nested interface method");
}
public static void main(String args[]){
MyInterfaceA.MyInterfaceB obj=
new NestedInterfaceDemo1();
obj.myMethod();
}
}
I have a requirement to invoke two different methods from two different classes to my own class and those two classes are in two different .jar files provided by the vendors.
The scenario is something like below:
abc.jar: public class A{ public void m1(){} }
xyz.jar: public class B{ public void m2(){} }
My own class is MyClass{}. If I have to use those two methods in my class I need to extend both the classes, but since java does't support multiple Inheritance, I am not able to achieve it.
Please share if there is any other way to access both m1() & m2() methods in my class.
Note: I have to extend the available functionalities and should customize the methods according to my requirement.
Edit: The question was clarified later, the OP wants to extend the functionalities of the classes.
One idea would be to create two separate sub-classes for the two different base classes. Extend the functionalities in these sub-classes and then use composition in your MyClass to use the functionalities of these sub-classes and their super-classes.
public class SubA extends A {
#Override
public void m1() {
// add extra functionalities
super.m1(); // invoke existing functionalities
}
}
public class SubB extends B {
#Override
public void m2() {
// add extra functionalities
super.m2(); // invoke existing functionalities
}
}
public class MyClass {
SubA a = new SubA();
SubB b = new SubB();
a.m1();
b.m2();
}
You can also refer to this question How do Java Interfaces simulate multiple inheritance? for detailed explanation of how to implement multiple-inheritance in Java.
Earlier answer:
Both the methods are public, so you don't need to extend the classes to use those methods. Just create an object of those two classes and call their respective methods.
A a = new A();
a.m1();
B b = new B();
b.m2();
Maybe I will do this,
class A{
public void m1{};
}
class B{
public void m2{};
}
class OneOverrideA extends A{
#Override
public void m1{};
}
class OneOverrideB extends B{
#Override
public void m2{};
}
class FatherClass extends OneOverrideA{
//well you have your class method m1 here but we cannot extend more than two class
public void m2{new OneOverrideB().m2()};
}
Although it is not awesome in my point of view, anyway why would you want to override both methods? if you're going to do that why not create them from zero? or are you going to use other methods from those class? nvm I would use composition anyway.
Hope it can re fresh your mind and get something from here :) GL
This question already has answers here:
Can we create an object of an interface?
(6 answers)
Closed 7 years ago.
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
interface ProgrammerInterview {
public void read();
}
class Website {
ProgrammerInterview p = new ProgrammerInterview() {
public void read() {
System.out.println("interface ProgrammerInterview class implementer");
}
};
}
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
Yes it is correct. you can do it with an inner class.
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc
I am programming a simple platformer game, and I have several types of platforms. I created a class for the most simple type and made the rest subclasses, with the only difference between each class being the value of their variables (so they all share the same variable and method names).
In my collision detection, I loop through a HashMap. Within that HashMap are ArrayLists of the instances of each class. But when I use a nested loop to loop through try to call their methods implicitly, I have found that I cannot access these methods without explicitly declaring which class I want to call the method from.
I have done research, although the only way I can see of doing this is to loop through the instances of each class separately, meaning one loop per class; I would rather not do this, since it would be a lot more code than I feel is necessary.
In order to be able to call a common method on classes of different types you need to give your objects a common supertype declaring the common method - i.e. they should have a common superclass, or implement a common interface.
Interfaces provide an easier way of declaring common functionality, because a class can implement multiple interfaces, but it can extend only one class.
Provide an interface with the common method, then declare the map to use objects of that interface, i.e.
interface CommonInterface {
void commonMethod(int arg);
}
class One implements CommonInterface {
public void commonMethod(int arg) {
...
}
}
class Two implements CommonInterface {
public void commonMethod(int arg) {
...
}
}
Here is what you can do now:
Map<String,CommonInterface> myMap = new HashMap<>();
myMap.put("one", new One());
myMap.put("two", new Two());
for (Map.Entry<String,CommonInterface> e : myMap.entrySet()) {
System.out.println(e.getKey());
CommonInterface c = e.getValue();
c.commonMethod(123);
}
Simple, make each platform class implement an IPlatform interface or extand a base class. Look up java polymorphism and interfaces.
Are your subclasses overriding the common methods from the super class?
In other words, are your subclass' common methods declared in your simpler class?
If it is the case, you can simply call the method as if it is a simple class:
public abstract class Fruit {
public abstract void method();
}
public class Apple extends Fruit {
#Override
public void method() {
System.out.println("I'm an apple");
}
}
public class Orange extends Fruit {
#Override
public void method()
System.out.println("I'm an orange");
}
}
Using this you can simply call your method from any fruit, since it has your method declared. No need to know which fruit it is. The following code:
Fruit fruit = new Orange();
fruit.method();
will output: "I'm an orange".