Aamir
Aamir

Reputation: 2424

Inner static classes in java

public interface Bsuper {

    abstract class A {
        abstract void test1();

        void test2() {
            System.out.print("test2 ");
        }
    }
}

// second file
public class Bsub extends Bsuper.A {

    void test1() {
        System.out.print("test1 ");
    }
}

// third file
public class Bsubmain {

    public static void main(String args[]) {
        Bsub sub1 = new Bsub();
        Bsuper.A obj = new Bsub();
        sub1.test1();
        sub1.test2();
        obj.test1();
        obj.test2();
    }
}

It produces the output as expected test1 test2 test1 test2, but my question is in the Bsuper class, class A is static we all know that and now with the abstract keyword it becomes abstract class, but how is it possible to have both abstract and static applied to class at the same time.Is class A really static also or is there any other explanation for it.Please answer!!

Upvotes: 1

Views: 79

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

Remember that a static inner class is using a different concept of static.

In this case it means that the inner class does not have access to the outer class's instance variables.

public class Test {
    long n = 0;

    static class A {
        // Not allowed.
        long x = n;
    }

    class B {
        // Allowed.
        long x = n;
    }

}

Making them abstract does not change anything.

    abstract static class C {
        // Not allowed.
        long x = n;
    }

    abstract class D {
        // Allowed.
        long x = n;
    }

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213243

how is it possible to have both abstract and static applied to class at the same time.

It is perfectly valid to have a static abstract class. This is different from having a static abstract method, which doesn't make sense, as you can't override such methods, and you're also making it abstract. But with static class, you can of course extend it, no issues. Making it abstract just restricts you with creating an instance of it.

So, even this is valid:

class Main {
    static abstract class Demo { }
    class ConcreteDemo extends Demo { }
}

In which case, you can't instantiate Demo, and sure you can instantiate ConcreteDemo.

Upvotes: 3

Related Questions