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

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

问题描述

所以我在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 是Message"类型.我以为所有抽象类都不能实例化?那么声明Message 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 (children) 的对象,让我们换一种方式,如果你有

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 优先)容器有 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

如果你定义抽象方法和抽象类的对象,你也可以创建抽象类的对象.

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-如何使用抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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