Java- How to use Abstract class

2019-07-16 05:32发布

So I was studying Abstract class in java, and when I was reading other people's codes I saw the following:

public abstract class Message implements Serializable, Comparable<Message> {
    //stuff in this class
}

In another class under the same project, the programmer declared a method as follows:

public void notifyMessage(Message msg, HostType sourceType) {
    //some stuff in this method
}

Notice in the notifyMessage declaration, variable msg is of type "Message". I thought all abstract classes cannot be instantiated? Then what does it mean to declare "Message msg"? Can someone explain what this means to me? Thanks in advance

2条回答
聊天终结者
2楼-- · 2019-07-16 05:40

Well that means that you can receive any object of type Message (children), let's put it in other way, if you have

public class Letter extends Message ...

you can send a Letter object as an argument for the notifyMessage

Something like this could be possible:

someObject.notifyMessage(  new Letter() , ... )

java.awt.Component is abstract JPanel inherits Container (actually JComponent first) Container have add(Component c)

That means that you can add any Component like JButton, JLabel, etc.

http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Container.html#add(java.awt.Component) http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html

You can also make objects of Abstract classes if you define abstract methods and body of that object.

    Message m = new Message() {
        //if no abstract method, then this is empty
    };
查看更多
三岁会撩人
3楼-- · 2019-07-16 05:44

basically, msg's actual class is a derived class of the type Message, but its reference type is that of message i.e. it is polymorphic. This is used if you have multiple subclasses for message, but are uncertain which of the subclasses will be referenced in the method. the code for this is

Message msg = new SubclassOfMessage()

But it is true you cannot have a new Message object

查看更多
登录 后发表回答