关于继承和多态的一个简单例子

package com;

class Super {
 public void opration(Super s) {
  System.out.println("Super operation!");
 }
};

class SuperA extends Super {
 public void opration(SuperA a) {
  System.out.println("SuperA operation A!");
 }

 public void opration(SuperB b) {
  System.out.println("SuperA operation B!");
 }

 public void opration(Super s) {
  if (s instanceof SuperB)
   System.out.println("S is a instance of Class SuperB!");
  if (s instanceof SuperA)
   System.out.println("S is a instance of Class SuperA!");
  if (s instanceof Super)
   System.out.println("S is a instance of Class Super!");
  System.out.println("SuperA operation S!");
  System.out.println();
 }
};

class SuperB extends Super {
 public void opration(SuperA a) {
  System.out.println("SuperB operation A!");
 }

 public void opration(SuperB b) {
  System.out.println("SuperB operation B!");
 }

 public void opration(Super s) {
  if (s instanceof SuperB)
   System.out.println("S is a instance of Class SuperB!");
  if (s instanceof SuperA)
   System.out.println("S is a instance of Class SuperA!");
  if (s instanceof Super)
   System.out.println("S is a instance of Class Super!");
  System.out.println("SuperB operation S!");
  System.out.println();
 }
};

public class Test {
 private static Super a;

 private static SuperB b;

 public static void main(String[] args) {
  b = new SuperB();
  a = new SuperA();
  System.out.println("Class name of variable a is " + a.getClass().getName());
  System.out.println("Class name of variable b is " + b.getClass().getName());
  System.out.println();
  a.opration(b);
  a.opration(a);
  b.opration(a);
  b.opration(b);
 }
}

 

结果为:

Class name of variable a is com.SuperA
Class name of variable b is com.SuperB

S is a instance of Class SuperB!
S is a instance of Class Super!
SuperA operation S!

S is a instance of Class SuperA!
S is a instance of Class Super!
SuperA operation S!

S is a instance of Class SuperA!
S is a instance of Class Super!
SuperB operation S!

SuperB operation B!

 

a是Super类型的引用,指向SuperA类型的对象!

  所以a只能调用类Super中存在的方法,

  如果方法被子类SuperA覆盖了,则调用子类SuperA中覆盖了的方法,

  对于子类中的新方法,a无权调用。

b是SuperB类型的引用,指向SuperB类型的对象!

  所以b可以调用类SuperB中所有的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值