用继承来简化调用不同子类的类似方法

来源:互联网 发布:卧龙01武将进阶数据 编辑:程序博客网 时间:2024/04/29 04:26

package lala;import java.util.*;class father{int x;void print(father f){System.out.println(f.x);}}class son extends father{//int x;//void print(son s){//System.out.println(s.y+"ydasdsad");//}//void print(father f){//System.out.println(f.x+"  asdsa");//}}class test{public static void main(String []args){son f = new son();f.x=2;f.print(f);}}
程序输出结果为2.当多个子类要使用父类中的print()方法,但传入的参数与子类本身相关时,生成一个子类对象,传入从父类继承的方法即可。

注意,如果子类中有成员变量  int x ,则输出结果为0.因为如果子类中定义了与父类相同的成员变量,在子类对象调用从父类继承的方法时,处理的是父类的变量,

当调用自己定义的方法时,才是处理的子类的变量


另有一句从其他地方看到的话,与方法不同,对象的属性不具备多态性。不解


0 0