我将在这里举例说明。 我知道Thor Thor类中的那些方法将覆盖Avengers Class中的方法。 (我将跳过方法的正文)
Class Avengers{
void hit(){
}
void walk(){
}
}
Class Thor extends Avengers{
void hit(){
}
void walk(){
}
void thunderSkill(){
}
}
这是Main。
public static void main(String[] args) {
Avengers thor = new Thor();
}
如果这样做,我可以使用'thor'实例访问那些hit()方法和walk()方法。但是我无法访问thunderSkill()方法。并且我意识到只能使用覆盖方法。我的问题是,在父类,复仇者类中,有什么方法可以访问thunderSkill方法而不重写thunderSkill吗?
因此,如果它还有其他英雄,例如雷神,钢铁侠,美国队长...等,他们 所有人都应该有自己独特的方法。如果我想通过实例访问这些唯一方法,那么是否所有这些唯一方法都必须在父类Avengers类中? (我正在尝试将实例的数据类型设置为“ Avengers”,以便在“ parameter”和“ argument”方面轻松进行。)
我是Java新手,请帮助我:)
谢谢你们!
答案 0 :(得分:0)
父类引用无法访问子类方法。如果使用Parent类引用,则只能调用重写的方法。
如果要使用子类方法,则有两个选项。 选项1:在Overridden方法内调用子方法。 (简单的) 选项2:您可以将父类引用与子类对象一起转换,并且可以调用子类方法。这是选项2的示例代码。
我建议您仔细阅读有关继承的Java文档。 https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
public class Parent {
public void canSpeak() {
System.out.println("I can speak");
}
public static void main(String[] args) {
Parent p = new Child();
p.canSpeak();
// p.canRead() // can not be accessed. because the refernece is parent.
// if you want to access the canRead() method in child class, then you need to case the object.
Child c = (Child)p;
c.canRead();
}
}
public class Child extends Parent {
/**
* This is the overridden method.
*/
@Override
public void canSpeak() {
System.out.println("I can speak");
}
/**
* Only child can read.
*/
public void canRead() {
System.out.println("I can read");
}
}
答案 1 :(得分:0)
您可以做的是使用界面。例如,定义:
public interface Superhero {
void superpower();
}
然后让Thor实现Superhero
,并像superpower
一样实现thunderSkill
。
要让英雄们拥有更多能力,您可以使用另一个界面:
public interface Superpower {
void useSuperpower();
}
然后使用Thunderskill
实现Superpower
,并使Avenger
类拥有一个List<Superpower>
,然后您可以相应地对其进行填充。