简体   繁体   中英

abstract class with published Api but default access constructor

In the MIDP api there is a public abstract class Layer , this class has a javadoc published however it doesn't show a constructor in the javadoc. In the same api there are two other classes Sprite and TiledLayer.

public class Sprite extends Layer
public class TiledLayer extends Layer

All these classes are in the package javax.microedition.lcdui.game

This means that the constructor of Layer has default access.

I wonder why the api of the class Layer has been published even though it cannot be sub-classed in user code?

The public interface of Layer is published because even though you cannot extend it you can still use it when you are referencing an instance of Sprite or TiledLayer polymorphically.

In other words it is possible to treat an instance of Sprite as an instance of Layer and as such it is important to know the public interface of Layer so that you know what members are available to work with.

Some objects can only be obtained through calling class factory methods (and, probably, you've noticed that GameCanvas objects have methods that will give you Layers). Other examples of class factories are in the XML package.

They could have declared Layer final but Layer is subclassed by other classes in the package and so that option was out.

But, generally, it's just a way of preventing subclassing (if using final is not an option).

The default constructor of a class has the same visibility as the class itself. Since Layer is public, it's default constructor is public, so it can be subclassed directly.

http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.8.9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM