Ques) Can we access the
non-final local variable inside the local inner class?
Ans: No
Ques) Can
we define an interface within the class?
Ans: Yes.
class A{
interface
Message{
void msg();
}
}
class TestNestedInterface2 implements A.Message{
public void
msg(){System.out.println("Hello nested interface");}
public static void
main(String args[]){
A.Message message=new
TestNestedInterface2();//upcasting here
message.msg();
}
}
Ques) Can we define a class within the interface?
Ans: Yes. If we define a class inside the interface, java compiler creates a static nested class.
To provide default implementation of an interface we can
define a class inside an interface
Interface
public interface VehicleService {
public void repair();
public class DefaultVehicle implements VehicleService{
@Override
public void
repair() {
System.out.println(" Default Repair");
}
}
public class busRepair implements VehicleService{
@Override
public void
repair() {
System.out.println(" Bus Repair");
}
public static void
main(String args[]){
busRepair b =
new busRepair();
b.repair();
DefaultVehicle
d = new DefaultVehicle();
d.repair();
}
}
Java Anonymous Implementer of
an Interface Type
interface Manageable
{
public void manage();
}
public class AnonymousInterfaceDemo
{
public static void main(String[] args)
{
Manageable m = new Manageable() {
public void manage()
{
System.out.println("It is manageable");
}
}; // anonymous interface implementer closes here
//m contains an object of anonymous interface implementer of Manageable.
m.manage();
}
}
Java Anonymous Inner Class in
Method Arguments
interface Manageable
{
public void manage();
}
class Manager
{
public void canManage(Manageable m)
{
m.manage();
}
}
public class MethodArgumentAnonymousClassDemo
{
public static void main(String[] args)
{
Manager m = new Manager();
m.canManage (new Manageable ()
{
public void manage()
{
System.out.println("Yes, it is being anonymously managed!");
}
}); // anonymous interface implementer as method argument closes here
}
}
Java doesn't have a diamond problem since interfaces don't contain
code.
A typical problem in OO programming is the diamond problem. I have
parent class A with two sub-classes B and C. A has an abstract method, B and C
implement it. Now I have a sub-class D, that inherits of B and C. The diamond
problem is now, what implementation shall D use, the one of B or the one of C?
Java knows no diamond problem. I can only have multiple inheritance
with interfaces and since they have no implementation, I have no diamond
problem. Is this really true?
yes, because you control the implementation of the interface in class.
Comments
Post a Comment