2

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?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Subhomoy Sikdar
  • 526
  • 5
  • 19

4 Answers4

4

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...

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thank you. Got the idea. But still thinking the usefulness of this. If I have to call it straight away then what is the point of using `Object` class? Instead we can name it as a new class `MyClass` and use it later on to call `myMethod()` similar to as antonio pointed out using an interface – Subhomoy Sikdar Feb 23 '15 at 10:48
1

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"
SMA
  • 36,381
  • 8
  • 49
  • 73
0

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();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

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();
    }
}
antonio
  • 18,044
  • 4
  • 45
  • 61