class Animal
{
static{
System.out.println("Animal静态代码块");
}
private String name;
private int age;
public Animal(){System.out.println("Animal无参数构造代码块");}
public Animal(String name,int age)
{
this.name=name;
this.age=age;
System.out.println("Animal构造代码块");
}
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public void speak()
{
System.out.println("大家好我叫"+name+"今年"+age+"岁");
}
public void eat()
{
System.out.println("主人,我饿了,咋们该吃饭了!");
}
public void run()
{
System.out.println("主人,你看我跑的多快!");
}
}
class Dog extends Animal
{
static
{
System.out.println("Dog静态代码块");
}
{
System.out.println("Dog构造代码块");
}
public Dog() {}
public Dog (String name,int age) {
super(name,age);
System.out.println("Dog构造方法");
}
public void eat()
{
super.eat();
//System.out.println("主人,我饿了,咋们该吃饭了!");
System.out.println("主人,我好像吃肉骨头!");
}
}
class Cat extends Animal
{
static{
System.out.println("Cat静态代码块");
}
{
System.out.println("Cat构造代码块");
}
public Cat(){}
public Cat (String name,int age)
{
super("喵喵",3);
System.out.println("Cat构造方法");
}
public void eat()
{
super.eat();
//System.out.println("主人,我饿了,咋们该吃饭了!");
System.out.println("主人,今中午吃鱼好不好嘛?喵喵...");
}
}
class AnimalTest
{
public static void main(String[] args)
{
Dog a= new Dog();
a.eat();
a.speak();
a.run();
a.setName("旺财");
a.setAge(5);
a.speak();
System.out.println("-----------------------------");
Cat b= new Cat();
b.eat();
b.speak();
b.run();
System.out.println("-----------------------------");
Cat c= new Cat("喵喵",3);
b.eat();
b.speak();
b.run();
}
}
在使用了子类的有参数构造方法,赋值之后,得到的结果还是默认的null和0,求大神解答!
|