1

Let ClassA represent an abstract class.

I'm wondering if it's possible to do something like this in Java:

public static abstract class ClassA {
    abstract void foo();
}

private ClassB extends ClassA a = new ClassA() {
     // define abstract methods here
     foo() { System.out.println("in anon!"); }

     // define OTHER variables here
     public int varB = 10;
}

// later... varB is not defined in ClassA, but it is in a.
// how can I access varB from a?
System.out.println(a.varB);

I want to make a special note: notice how I'm printing varB. Say varB was NOT defined in ClassA, only in the anonymous inner class.

I have a lot of abstract classes wherein I define their abstract methods on the fly when I create them. However, I would also like to treat these classes as their own type because sometimes I need to access variables from that class that are specific to that version of the object.

Is there a way of doing something similar to what I've shown above, or do I need to create a "ClassB" that extends from "ClassA" every time?

Is there some type of workaround?

Thanks

4
  • Possible duplicate of Java:can annonymous inner classes extend? Commented Mar 16, 2017 at 7:12
  • I think I found what you're looking for, I have updated my answer. Commented Mar 16, 2017 at 8:39
  • Impossible without using reflection. Commented Mar 17, 2017 at 7:23
  • Hmm, yeah, seems like the only way to do this is with reflection or defining a class inheritance. Commented Mar 17, 2017 at 14:38

3 Answers 3

4

Try Java Anonymous inner classes. sample as below :

abstract class ClassA {  
 abstract void eat();  
}  
class TestAnonymousInner{  
 public static void main(String args[]){  
  ClassA p=new ClassA (){  
    void eat(){System.out.println("nice fruits");}  
  };  
  p.eat();  
}  
}  

EDIT:

As far as accessing the variable varA is concerned, you need to declare that variable in the Abstract class, as ClassA needs the information about the variable. Here we can treat object referred by p as the child class of ClassA which referred by its parent's reference, and hence parent does not have access to the methods and variable introduced in the child class( in this case the anonymous class ).

Sign up to request clarification or add additional context in comments.

2 Comments

My problem is that if I created a new variable called, say, "varA", in the new anonymous class, even though I'd make "varA" public, I wouldn't be able to access varA like I would "eat".
@Luca, Please find the edited portion, you can not even access eat() if it is not mentioned in the abstract class definition.
2

Would anonymous classes not suit your usecase?

public static void main(String[] args) {
    // Make an anonymous instance of A
    final A first = new A() {
        private final int i = 10;

        void foo() {
            System.out.println(i);
        }
    };

    // Make another anonymous instance of A
    final A second = new A() {
        private final String message = "Listen!";

        void foo() {
            System.out.println("Hey!");
            System.out.println(message);
        }
    };

    // They do their own unique things
    first.foo();
    second.foo();

    // Both have A as a super-type
    System.out.println(first instanceof A);
    System.out.println(second instanceof A);

    // But first and second are *not* A and therefore not the same class!
    final boolean isSameClass = first.getClass().equals(second.getClass());
    System.out.println(isSameClass);
  }

  static abstract class A {
     abstract void foo();
  }

The idea here is that when you make a new anonymous class, you're actually sub-typing the class you use for a single instance. This is part of the reason why double brace initializers are a bad idea!

EDIT: Accessing a variable that belongs solely to an anonymous class is not possible. However if you're okay with reflection, something like this could work:

try {
    final Field i = first.getClass().getDeclaredField("i");
    i.setAccessible(true);
    System.out.println(i.getInt(first));
} catch (NoSuchFieldException | IllegalAccessException e) {
    e.printStackTrace();
}

This is pretty messy and I wouldn't necessarily recommend it, but it does accomplish what you're setting out to do here.

3 Comments

I've edited my post to make things more clear. Imagine I'm trying to access a variable or method from outside that is specific to that anonymous instantiation.
Unfortunately this is a limit of static typing. You can read more about it here: stackoverflow.com/questions/6459298/…
Ahh. Thanks a lot for the reference! :)
0

You can define a new class locally in a method.

I have added a new class MixA int the method main. Just for sake of see how it works this class extends an abstract class ClassA and implements an interface AInterface but you don't need to do this, just extends or implement what you need.

So given the the class is defined you can at compile time find every method or public you add:

abstract class ClassA {
  abstract void doThis();
}

interface AInterface {
  public int getInternalValue();
}

public class TestAnonymousInner {
  public static void main(String args[])
  {

     class MixA extends ClassA implements AInterface {

      public int varB = 10;

      @Override
      public int getInternalValue()
      {
        return 0;
      }

      @Override
      void doThis()
      {
      }

    }

    MixA b = new MixA();    
    b.getInternalValue();
    b.doThis();

    System.out.println(b.varB);

  }
}

1 Comment

I understand, but the problem is that I want to access varB even though it is not defined in AClass or AInterface.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.