Can We Create Public Static Abstract Class in Java?

Can We Create Public Static Abstract Class in Java?

I was searching in google for something and I got a code like

public static abstract class LocationResult{
    public abstract void gotLocation(Location location);
}

It's a nested class but wondering how it could be accessible ?

1

2 Answers

It must be a nested class: the static keyword on the class (not methods within it) is only used (and syntactically valid) for nested classes. Such static member classes (to use Java in a Nutshell's common nomenculture) hold no reference to the enclosing class, and thus can only access static fields and methods within it (unlike non-static ones; see any summary of nested classes in Java (also known as inner classes).

It can be accessible like this:

public class EnclosingClass {
  public static abstract class LocationResult{
    public abstract void gotLocation(Location location);
  }
}

EnclosingClass.LocationResult locationResult = ...
6

Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.

So you could create a class extending it using extends Mainclass.LocationResult and use it with Mainclass.LocationResult instance = ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.