Reputation: 674
I am creating an Object as a class variable with anonymous type. There are no compilation errors. My question is how to use the class? How to call the methods that I am defining? Where is it used actually?
public class MyClass {
Object o = new Object(){
public void myMethod(){
System.out.println("In my method");
}
};
}
I am not able to call the myMethod()
of object o. How to do that and when do we use this?
Upvotes: 2
Views: 80
Reputation: 18242
You can use interfaces:
public interface MyInterface {
public void myMethod();
}
In your MyClass
public class MyClass {
MyInterface o = new MyInterface() {
@Override
public void myMethod() {
System.out.println("In my method");
}
};
public void doSomething() {
o.myMethod();
}
}
Upvotes: 0
Reputation: 328618
The only way to call a method of an anonymous class that is not part of the super class methods is to call it straight away:
new Object(){
public void myMethod(){
System.out.println("In my method");
}
}.myMethod();
If you just store the anonymous class in an Object
variable you won't be able to call its method any more (as you have figured out).
However the usefulness of such a construct seems quite limited...
Upvotes: 4
Reputation: 691755
Your variable type is Object
, so the only methods that the compiler will let you call are the ones declared in Object
.
Declare a non-anonymous class instead:
private static class MyObject {
public void myMethod() {
System.out.println("In my method");
}
};
MyObject o = new MyObject();
Upvotes: 0
Reputation: 37023
To do something like this, you should be having a method in Object class. This in short means you need to override the method defined in Object class.
Try something like:
Object o = new Object(){
public boolean equals(Object object){
System.out.println("In my method");
return this == object;//just bad example.
}
};
Object o2 = new Object();
System.out.println(o.equals(o2));will also print "In my method"
Upvotes: 1