Java-如何使用Abstract类 [英] Java- How to use Abstract class

查看:341
本文介绍了Java-如何使用Abstract类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在研究Java中的Abstract类,当我阅读其他人的代码时,看到了以下内容:

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
}

notifyMessage声明中的通知,变量msg为类型为消息。我以为所有抽象类都不能实例化?那么,声明消息消息是什么意思?有人可以向我解释这意味着什么吗?预先感谢

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

推荐答案

好,这意味着您可以接收任何类型为Message(孩子)的对象,让我们用其他方式,如果您有

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 ...

您可以发送Letter对象作为notifyMessage的参数

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

可能会发生以下情况:

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

java.awt.Component是抽象的
JPanel继承了Container(实际上是JComponent在先)
Container具有add(Component c)

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

这意味着您可以添加任何组件,例如JButton,JLabel等。

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

如果定义了抽象方法和对象的主体,也可以使对象成为Abstract类。

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

这篇关于Java-如何使用Abstract类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆