java吧 关注:1,247,401贴子:12,727,747
  • 3回复贴,共1

问一下在主类中定义方法

只看楼主收藏回复

比如Simulator simulator=new simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
请问该如何在主类中定义


IP属地:湖北1楼2013-04-20 22:56回复
    多态


    IP属地:江苏2楼2013-04-21 00:03
    回复
      public class Simulator {
      //Simulator s;
      public void playSound(Simulator s){
      //this.s = s;
      //return s;
      }
      }
      public class Dog extends Simulator{
      public Dog(){
      System.out.println("Dog");
      }
      }
      public class Cat extends Simulator{
      public Cat(){
      System.out.println("Cat");
      }
      }
      public class Test {
      public static void main(String[] args) {
      new Simulator().playSound(new Dog());
      new Simulator().playSound(new Cat());
      }
      }
      实验结果:
      Dog
      Cat
      不知道是不是这意思。


      IP属地:江苏3楼2013-04-21 00:15
      收起回复