继承-多态-访问控制.pptVIP

  • 2
  • 0
  • 约8.65千字
  • 约 38页
  • 2016-08-30 发布于浙江
  • 举报
继承-多态-访问控制

* == 与 继承 对于引用型,== 两边的变量必须是同种类型或有继承关系。例如: A 为 B 父类;A为C 父类;B、C 无继承关系 A aB = new B(); A aC = new C(); B b = (B) aB ; C c = (C) aC ; System.out.println ( b == aB ); System.out.println ( aB == aC ); System.out.println ( b == c); * instanceof 运算符 用于判断在运行时所引用的对象的实际类型,用法: 变量 instanceof 类型 如果变量与类型相同,或者是类型的子类型,则结果就是true * instanceof 运算符2 public class Person extends Living{…} public class Student extends Person {…} public class Graduate extends Student {…} ------------------------------------------------------------ public void method1(Person e) { if (e instanceof Student) { // 处理Student类型及其子类类型对象 } else if (e instanceof Graduate) { //处理Graduate类型及其子类类型对象 } else { //处理Person类型对象 } } * 子类中添加的属性与方法 一个引用类型变量如果声明为父类的类型,尽管实际引用的是子类对象,但是该变量就不能再访问子类中添加的属性和方法 Student m = new Student(); m.school = pku; //合法 Person e = new Student(); e.school = pku; //非法 * 对象造型举例 public class Test{ //Person及Student类的定义如前 public void method(Person e) { // System.out.pritnln(e.getschool()); //非法 if(e intstanceof Student){ Student me = (Student)e; System.out.pritnln(me.getschool()); } } public static void main(Stirng args[]){ Test t = new Test(); Student m = new Student(); t.method(m); } } * 正常的方法调用 Person e = new Person(); e.getInfo(); Student e = new Student(); e.getInfo(); 虚拟方法调用(多态情况下) Person e = new Student(); e.getInfo(); 父类当中被隐藏的域呢? 子类中隐藏的属性与覆盖的方法 * 多态举例 public class Test{ public static void main (String[] args){ Base b = new Subclass(); System.out.println(b.x); System.out.println(b.method()); } } class Base{ int x = 2; int method(){ return x; } } class Subclass extends Base{ int x = 3; int method (){ return x ; } } * java多态性说明 访问一个对象的非静态方法,运行时与实际引用的对象的方法绑定。 访问一个对象的的成员变量(包括静态变量和实例变量),运行时与声明的类的成员变量绑定。 访问一个引用型的变量的静态方法,运行时与声明的类的方法绑定。 * 在这简单介绍一下Object类的一些方法:equals(), wait(), notify(), notifyAll(), toString() * 是不是子类的成员变量

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档