John smith
John smith

Reputation: 1785

How to extends Abstract Inner Class in java

I confused if

Abstract Class A{method();method2();}

And Other Class B Which Have Inner Class C

Class B{Abstract Class C{method(){//body}}}

And now Question is how to extends Class C b/C Abstract Class must be extends else this is Unused class.

Upvotes: 2

Views: 6749

Answers (2)

Filip Bulovic
Filip Bulovic

Reputation: 1816

You simply extend it

class B{abstract class C{abstract void method();}}
class D extends B{
    class E extends C{
        void method(){
            System.out.println("Hello World");
        }
    }
}

Or slightly more complicated without extending outer class

class B{abstract class C{abstract void method();}}
public class F extends B.C{
  F(B b){
      b.super();
  }
  void method(){
      System.out.println("Hello World");
  }
  public static void main(String[] args){
      B b = new B();
      F f = new F(b);
      f.method();
  }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500595

First, let's make it simpler - this has nothing to do with Android directly, and you don't need your A class at all. Here's what you want:

class Outer {
    abstract class Inner {
    }
}

class Child extends Outer.Inner {
}

That doesn't compile, because when you create an instance of Child you need to provide an instance of Outer to the Inner constructor:

Test.java:6: error: an enclosing instance that contains Outer.Inner is required
class Child extends Outer.Inner {
^
1 error

There are two options that can fix this:

  • If you don't need to refer to an implicit instance of Outer from Inner, you could make Inner a static nested class instead:

    static abstract class Inner {
    }
    
  • You could change Child to accept a reference to an instance of Outer, and use that to call the Inner constructor, which uses slightly surprising syntax, but works:

    Child(Outer outer) {
        // Calls Inner constructor, providing
        // outer as the containing instance
        outer.super();
    }
    

Note that these are alternatives - you should pick which one you want based on whether or not the inner class really needs to be an inner class.

Upvotes: 11

Related Questions