public class Parent2 { //类变量,Parent2的类别 public static String kind = "com.baodian.unit2.Parent2"; //类变量,Parent2的年龄 public static int age = 50; //实例变量,Parent2的名字 public String name = "Parent2"; /** * 静态方法,获取parent2的类别 * @return */ public static String getKind() { System.out.println("Parent2的getKind()方法被调用了"); return kind; } /** * 静态方法,获取Parent2的年龄 * @return */ public static int getAge() { System.out.println("Parent2的getAge()方法被调用"); return age; } /** * 实例方法,获取Parent2的名字 * @return */ public String getName() { //实例方法中操作的可以是实例变量,也可以是类变量 System.out.println("Parent2的getName()方法被调用了!"); return null; } /** * final方法,将Parent年龄加1 * @return */ public final int nextAge() { return ++age; } }
public class Child2 extends Parent2 { //类变量,Child2的类别 public static String kind="com.baodian.unit2.Child2"; //实例变量,Child2的年龄,在Parent2类中是static的 public int age = 25; //实例变量,Child2的名字 public String name="Child2"; /** * 静态方法,获取Child2的类别 * @return */ public static String getKind() { System.out.println("Child2的getKind()方法被调用了"); return kind; } /** * 静态方法,获取父类的名字 * @return */ public static String getParentKind() { //通过类名加"."访问父类中被隐藏的类变量 return Parent2.kind; } /** * 实例方法,获取Child2的名字 */ public String getName() { System.out.println("Child2的getName()方法被调用了"); return this.name; } /** * 实例方法,获取父类的名字 * @return */ public String getParentName() { //通过super关键字父类中被隐藏的实例变量 return super.name; } /* * 错误!!!,实例方法不能覆盖父类的静态方法 public int getAge() { return this.age; } */ /* * 错误!!!父类的final方法不能够被覆盖 public int nextAge() { return ++age; } */ }
/** * * 方法和变量在继承时的覆盖与隐藏 */ public class CoverHideTest { public static void main(String args[]) { //先测试继承时变量的覆盖与隐藏问题 Child2 child = new Child2(); System.out.println("child name:" + child.name + "; age:" + child.age + "; kind:" + child.kind); //此处得到的都是Child2类的变量值 //将child类型转换成Parent对象 Parent2 parent = child; System.out.println("转换成Parent2后name:" + parent.name + "; age:" + parent.age + "; kind:" + parent.kind); //此处得到的都是Parent2类的变量值 System.out.println(); System.out.println("子类访问父类被隐藏的实例变量name: " + child.getParentName()); System.out.println("子类访问父类被隐藏的静态变量kind: " + child.getParentKind()); //再测试继承时方法的覆盖与隐藏问题 System.out.println(); child.getName(); //实例方法 child.getKind(); //静态方法 parent.getName(); //实例方法 parent.getKind(); //静态方法 } }