• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Jay_zhen
博客园    首页    新随笔    联系   管理    订阅  订阅
OOP特征三:Polymorphism多态性 Instanceof

多态性:一个事物的多种形态
使用前提: ① 类的继承关系 ② 方法的重写

Person p1 = new Man();
父类的引用 指向 子类的对象(或 子类的对象 赋给 父类的引用 )

只适用于方法,不适用于属性(编译和运行都看左边)!

class Base {
	int count = 7;
	public void display() {
		System.out.println(this.count);
	}
}

class Sub extends Base {
	int count = 17;

	public void display() {
	  System.out.println(this.count);
	}
}

public class FieldMethodTest {
	public static void main(String[] args) {
		Sub s = new Sub();
		System.out.println(s.count);//17
		s.display();//17
		
		Base b = s;   //多态性 赋值就是地址
		//== :比较的是两个引用数据类型变量的地址值是否相同
		System.out.println(b == s);//true
		System.out.println(b.count);//7,属性值没有改变
		b.display(); //17,但方法改变了
	}
}

虚拟方法调用

编译,看左边;运行,看右边。在编译期,只能调用父类中声明的方法,但在运行期,我们实际执行的是子类重写父类的方法。
Instanceof 亲子鉴定

点击查看`Instanceof`操作符
public class PersonInstanceof {

    public static void main(String[] args) {

        PersonInstanceof test = new PersonInstanceof();
        
        test.method( new Person() );
        System.out.println("************");
        
        test.method( new Student() );
        System.out.println("************");
        
        test.method( new Graduate() );
    }


    public void method( Person e ){

        //虚拟方法调用
        String info = e.getInfo();
        System.out.println(info);

        //测试方法一
		if(e instanceof Graduate){
			System.out.println("a graduated student");
			System.out.println("a student");
			System.out.println("a person");
		}else if(e instanceof Student){
			System.out.println("a student");
			System.out.println("a person");
		}else{
			System.out.println("a person");
		}

            //测试方法二
        /*
        if(e instanceof Graduate){
            System.out.println("a graduated student1");
        }

        if(e instanceof Student){
            System.out.println("a student1");
        }

        if(e instanceof Person){
            System.out.println("a person1");
        }

*/
    }
}

class Person {
    protected String name = "Liuzhen";
    protected int age = 23;

    public String getInfo() {
        return "PersonName: " + name + "\n" + "Personage: " + age;
    }
}

class Student extends Person {
    protected String school = "SHU";

    public String getInfo() {
        return "StudentName: " + name + " age: " + age + " school: " + school;
    }
}

class Graduate extends Student {
    public String major = "Math";

    public String getInfo() {
        return "Name: " + name + "\nage: " + age + "\nschool: " + school + "\nmajor:" + major;
    }
}

RunResult:

posted on 2021-12-29 09:49  Jay_zhen  阅读(44)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3