Java类,要么与另一个类完全相同,要么相似,但添加了方法。

huangapple go评论60阅读模式
英文:

Java classes that are either the exact same as another class, or is the same, but has added methods

问题

我是 Java 类的新手。

我在这里有两个问题。

问题1:我想要创建一个名为 "ClassA" 的类,并且我希望它与 Vaadin 创建的名为 "Component" 的类相同。所以当我写下:

ClassA classA = new ClassA();

它与以下代码相同:

Component component = new Component();

这是否有可能?

问题2:我想要创建 "ClassA",使其与 Vaadin 的 "Component" 类相同,但我也希望能够向这个 "ClassA" 类添加自己的方法。

希望你能帮助。

英文:

I am new to java classes.

I have a two problem here.

Problem 1: I want to create a class called "ClassA", and I want it to be the same as class made by Vaadin called "Component". So when I write

ClassA classA = new ClassA();

It is the same as:

Component component = new Component();

How is that possible?

Problem 2: I want to create "ClassA", I want it to be the same as Vaadin class 'Component', but I also want to be able to add own methods to this "ClassA".

I hope you can help.

答案1

得分: 2

你可以扩展类以使用它们的方法,同时仍然能够向你的类中添加自己的方法(除非被扩展的类是final的)。

class ClassA extends ClassB {
    // 不要忘记构造函数
}

但在这种情况下,这样做是行不通的,因为Component似乎是一个接口。所以你只能实现这个接口,但必须自己创建所有的方法。

class ClassA implements Component {
    // ...
}

这可能需要很多工作,因此尝试找到Component的一个实现,然后你可以扩展那个实现。

英文:

You can extend classes to use their methods and still able to add your own methods to your class (unless the extended class is final).

class ClassA extends ClassB {
    // don't forget constructor
}

But in this case, this won't work because Component seems to be an interface. So you can just implement the interface but have to create all the methods by yourself.

class ClassA implements Component {
    ...
}

This might be a lot of work so try to find an implementation of Component and then your can extend that implementation.

huangapple
  • 本文由 发表于 2020年9月21日 16:08:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63988383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定