简体   繁体   中英

Java- How to use Abstract class

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

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
    };

basically, msg 's actual class is a derived class of the type Message, but its reference type is that of message ie 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

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