继承

Java的继承

在没有调用父类的setter和getter方法时,继承只能是父类向下传递数据,而子类无法向父类传递数据  

//定义Fruit父类
class Fruit {
    private int weight = -1;
    public  void info()
    {
        System.out.println("I am  a fruit ,and I weight "+ weight+" g !");
    }

    public void setWei(int weight) {
        this.weight = weight;
    }

    public int getWei() {
        return weight;
    }
}

//定义子类
class Appple extends Fruit {
    int weight = 0;
}

//测试代码
public class Test {
    public static void main(String[] args) {
        Appple a = new Appple();
        a.setWei(6);
        a.weight = 10;
        a.info();
        System.out.println("the weight of SuperClass is "+a.getWei());
        System.out.println("the weight of SubClass is "+a.weight);
    }
}

运行结果为:

I am  a fruit ,and I weight 6 g !
the weight of SuperClass is 6
the weight of SubClass is 10

由于子类中没有info(),方法,因此子类在调用父类的info()方法时,info()方法中的weight是父类的变量,而不是子类中的变量。当代码改成以下情况时,结果就非常明显了。

public class Test {
    public static void main(String[] args) {
        Appple a = new Appple();
        a.weight = 10;
        a.info();
        System.out.println("the weight of SuperClass is "+a.getWei());
        System.out.println("the weight of SubClass is "+a.weight);
    }
}

运行结果如下:

I am  a fruit ,and I weight -1 g !
the weight of SuperClass is -1
the weight of SubClass is 10

可以看到在不调用setter方法时,父类的weight是不会改变的,因此info()方法调用父类自己的变量weight
因此可以调用父类的settergetter方法对父类的进行操作。

你可能感兴趣的:(Java)