下面程序哪里错呢?(小白一个,别介)

来源:9-1 Java 中的继承

guangnian

2015-11-07 11:23

 public class Animal { public int age; public String name; public void eat(){ System.out.println("动物具有吃东西的能力"); } public class Dog extends Animal{ } public static void main(String[] args) { Dog dog=new Dog(); dog.age=10; dog.name="xiaotian"; dog.eat(); } }

写回答 关注

3回答

  • 半成品LY
    2015-12-14 15:49:23

    你写的这个代码读起来很不方便。

  • 贪_
    2015-11-27 08:57:50

    不要将子类定义在父类里面

     public class Animal {

             public int age; 

             public String name; 

             public void eat(){ 

                System.out.println("动物具有吃东西的能力"); 

           } 

    }

    public class Dog extends Animal{ } 

    public class text{

                 public static void main(String[] args) 

                 { 

                     Dog dog=new Dog(); 

                     dog.age=10; dog.name="xiaotian"; 

                     dog.eat(); 

                 } 

    }


  • clay_cai
    2015-11-09 17:36:00

    public void eat(name,age){ System.out.println(name+age+"岁具有吃东西的能力"); }

    public static void main(String[] args) { Dog dog=new Dog(); dog.age=10; dog.name="xiaotian"; dog.eat(dog.name,dog.age); } }

    或者

    import ……Dog;

     public class Animal { public void eat(Dog dog){ System.out.println(dog.name+dog.age+"岁具有吃东西的能力"); } public class Dog extends Animal{ } public static void main(String[] args) { Dog dog=new Dog(); dog.age=10; dog.name="xiaotian"; dog.eat(dog); } }

    输出:xiaotian10岁具有吃东西的能力

Java入门第二季 升级版

课程升级!以终为始告别枯燥,在开发和重构中体会Java面向对象编程的奥妙

530099 学习 · 6086 问题

查看课程

相似问题