Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Class in Abstract Class

abstract class MyClass{

    static class StaticClass{
        public void showAdd(){
            System.out.println(" show add");
        }
    }
}

public class SampleClass extends MyClass{

    public static void main(String[] args){
         MyClass myClass = new SampleClass();
         MyClass.StaticClass staticClass = new MyClass.StaticClass();
         staticClass.showAdd();
    }
}

Output is proper as expected but how can we write new with an abstract class??

like image 440
Jaikrat Avatar asked Mar 29 '26 19:03

Jaikrat


2 Answers

You are not doing new on the abstract class but on the inner class that exists in this abstract class. In this case the abstract class is acting as a namespace.

like image 90
vainolo Avatar answered Apr 02 '26 02:04

vainolo


You cannot instantiate an abstract class. Your example "works" because you are not really instantiating an abstract class.

MyClass myClass = new SampleClass();

SampleClass is a child and an implementation of the MyClass class, and because of that it is not abstract. So that line simply works as it should. Try replace new SampleClass() to new MyClass() and you will get an compiler error.

MyClass.StaticClass staticClass = new MyClass.StaticClass();

which is the same in this case as:

StaticClass staticClass = new StaticClass();

Is just an instantiation of a Inner Class declared inside an abstract class. Since this inner class is not abstract it may be instantiated.

like image 20
Filipe Palrinhas Avatar answered Apr 02 '26 02:04

Filipe Palrinhas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!