Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class with nested class, is this possible?

Tags:

java

If I write an abstract class, then nest a class in the abstract class, will I have access to its methods in any subclasses of the abstract class? I cannot find the answer anywhere..

like image 965
providence Avatar asked Mar 15 '11 20:03

providence


People also ask

Can abstract class be nested in Java?

As for how to extend an abstract nested class... It's the same as extending a concrete nested class, except that you need to implement any abstract methods (just as you would if you were extending a top-level abstract class).

Can we have abstract inner class?

Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete).

Can we do multiple inheritance with abstract classes?

Abstract classes do not support multiple inheritance.

Can abstract class have constructor?

An abstract class can have an abstract and a non-abstract method. It must be declared with an abstract keyword. It can have a constructor, static method.


2 Answers

Of course, access modifiers on inner classes obey the same rules as on fields and methods. It does not matter whether your class is abstract or concrete, as long as the nested class is either public, protected or the subclass is in the same package and the inner class is package private (default access modifier), the subclass will have access to it.

public abstract class AbstractTest {

    // all subclasses have access to these classes
    public class PublicInner {}
    protected class ProtectedInner {}

    // subclasses in the same package have access to this class
    class PackagePrivateInner {}

    // subclasses do not have access to this class
    private class PrivateClass {}

}
like image 97
krock Avatar answered Oct 13 '22 09:10

krock


class Abstract {
    modifier1 class Nested { modifier2 int i = 0; }
    Abstract() {
        Nested n = new Nested();
        n.i = 1;
    }
}

class Sub extends Abstract {
    Sub() {
        Nested n = new Nested();
       // have access as long you not choose "private"
       // for `modifier1` or `modifier2`:
        n.i = 5;
    }
}
like image 29
binuWADa Avatar answered Oct 13 '22 11:10

binuWADa