2 回答
TA贡献1848条经验 获得超6个赞
您可以在SportTest构造函数中获取Sport类,因此您可以访问Sport类以及Football and Hockey类:
public class Sport(){
public Football football;
public Hockey hockey;
public Sport(){
football = new Football();
hockey = new Hockey();
}
}
public class Football{
String getName(){return "Football";}
}
public class Hockey{
String getName(){return "Hockey";}
}
public class SportTest{
public SportTest(Sport sport){
sport.football.getName(); // "Football"
sport.hockey.getName; // "Hockey"
}
}
或者,而不是在体育课上举行足球和曲棍球比赛。您可以将Sport设置为界面,并在Football和Hockey类中实现Sport:
public interface Sport(){
String getName();
}
public class Football implements Sport{
@Override
String getName(){return "Football";}
}
public class Hockey implements Sport{
@Override
String getName(){return "Hockey";}
}
public class SportTest{
public SportTest(Sport sport){
sport.getName();
}
}
SportTest footballTest = new SportTest(new Football()); // "Football"
SportTest hockeyTest = new HockeyTest(new Hockey()); // "Hockey"
TA贡献1827条经验 获得超8个赞
您需要对extend一个类和implement另一个类进行多重继承,这样才能访问方法。
例如。以下是进行多重继承的伪代码:
class A{
public:
void method1();
}
interface B{
public:
abstract void method2();
}
class C extends A implements B{}
C c = new C();
c.method1();
c.method2();
添加回答
举报