父类引用指向子类对象时变量传递问题

xiaoxiao2021-02-28  119

在复习Super的时候想到父类引用指向子类对象时调用方法传递和变量传递问题,学习时间较短,仅供参考。 代码如下:

package com.newterm; public class SuperDemo { public static void main(String[] args) { Father2 fa = new Father2(); fa.play(); fa.run(); // fa.age; // fa.age=20; System.out.println("______________"); Son2 s = new Son2(); s.play(); s.run(); // s.age; System.out.println("______________"); Father2 faa = new Son2(); // faa.age; faa.play();// play重写了 faa.run();// run用super调用 // Son2 ss=new Father2(); System.out.println("______________"); // Object f=new Father2(); // Object son=new Son2(); System.out.println(fa.age + " " + s.age + " " + faa.age);// 重写了faa的age //属性不能被重写 } } class Father2 { int age = 18; void play() { System.out.println("father play"); } void run() { System.out.println("father run"); } } class Son2 extends Father2 { int age = 6; void play() { System.out.println(" son play"); } void run() { super.run(); } }

结果如下: father play father run


son play father run


son play father run


18 6 18

转载请注明原文地址: https://www.6miu.com/read-30918.html

最新回复(0)