当前位置: 代码迷 >> J2SE >> 多态有关问题
  详细解决方案

多态有关问题

热度:113   发布时间:2016-04-24 12:53:23.0
多态问题
// polymorphism/biking/Biking.java
// TIJ4 Chapter Polymorphism, Exercise 1, page 281
/* Create a Cycle class, with subclasses Unicycle, Bicycle and Tricycle.
* Demonstrate that an instance of each type can be upcast to Cycle via a ride()
* method.
*/
package polymorphism.biking;
//import static org.greggordon.tools.Print.*;

class Cycle {
private String name = "Cycle";
public static void travel(Cycle c) {
System.out.println("Cycle.ride() " + c);
}
public String toString() {
return this.name;
}
}

class Unicycle extends Cycle {
private String name = "Unicycle";
public String toString() {
return this.name;
}
}

class Bicycle extends Cycle {
private String name = "Bicycle";
public String toString() {
return this.name;
}

}

class Tricycle extends Cycle {
private String name = "Tricycle";
public String toString() {
return this.name;
}
}

public class Biking {
public static void ride(Cycle c) {
c.travel(c);
}

public static void main(String[] args) {
Unicycle u = new Unicycle();
Bicycle b = new Bicycle();
Tricycle t = new Tricycle();
ride(u);
ride(b);
ride(t);
}
}

c.travel(c); 这里为什么不写Cycle.travel(c)?搞的我有点晕了

------解决方案--------------------
c.travel(c); 这里为什么不写Cycle.travel(c)?搞的我有点晕了


没看懂啥意思?
Cycle 是一个类,难道那个 travel是一个静态方法吗?
c 是 Cycle的实例,当然可以用 c.来调用
  相关解决方案