Forums Register Login

Doubt on Class defined inside an interface

+Pie Number of slices to send: Send
Can any one tell the correct answer for the following question and explain why?
Q: Which of the following are true about the class defined inside an interface
ANS:
1).it is not possible in the java Language.
2).The class is always public.
3).The class is always static.
4).the class methods cannot call the methods declared in the interface.
5).the class methods can call only the static methods declared in the interface.
The answer given was 2, 3 and 4

Thanks, Anand
+Pie Number of slices to send: Send
Anand,
Basically when you create a class which implements the interface, the class
defined inside the interface becomes an inner class.
The 5th option is wrong because you cannot have a static method declared in an interface anyway.(It's illogical!!)
The 4th option is correct because it follows from above that in order to call the(non-static method)of the interface you need a reference of that interface type inside that class which is obviously not possible.
However the 2nd and 3rd option does not seem to be right.Have a look at the code below which compiles and gives an output, though the class is neither
static nor public .
Code:-
public interface ClassInterface {
// Class defined inside the interface
class Inner {
int var1=7;
int var2=9;
String innerMethod1(){
//The line below does not compile-non-static method cannot be referenced in a static context
//System.out.print(mtd1());
return "return from innerMethod1 of class Inner";
}
}
// Method of the interface
public String mtd1();
}

public class TestClass implements ClassInterface{
public static void main(String[] args) {
TestClass testClass1 = new TestClass();
// one way to access class Inner
System.out.println(new ClassInterface.Inner().var1);
// another way to access class inner
System.out.println(new TestClass.Inner().innerMethod1());
}
public String mtd1(){
return "pallavi";
}
}
OUTPUT:-
7
return from innerMethod1 of class Inner
Also do consider the situation in which you would require writing such code.
Hope this was of some help,
Pallavi
+Pie Number of slices to send: Send
Pallavi,
Thanks for the explanation. That was helpful.
I found that option 2 and 3 are correct in another forum.
By Java spec ,an interface by default makes all members public,static even when a modifier isn't specified.
Anand
Don't listen to Steve. Just read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 778 times.
Similar Threads
doubt : class defined inside an interface
Question on Interface
class inside interface
class defined inside an interface
Question on Interface
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:45:52.