5_Java面向对象思想和概念.ppt
文本预览下载声明
对于this的第二种用法(作用),看以下例子 设计一个程序测试一下类有无public访问控制符的区别? 自己写个程序测试一下成员变量或成员函数的访问权限? 类中的常量 类中的常量是被该类的所有对象共享的,因此,常量应该声明为final static。 例如,Math类中的常量PI是这样定义的: final static double PI = 3.14159265358979323846 Immutable Objects and Classes Example What Class is Immutable? 然而,不好的重载兼容,会发生有歧义的重载: public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); }? public static double max(int num1, double num2) { if (num1 num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 num2) return num1; else return num2; } } 多态(Polymorphism) Polymorphism源于希腊文,意思是“多种形式” 定义:使用父类对象的地方都可以使用子类的对象,这就是所谓的多态。 简单来说:多态意味着父类型的变量可以引用子类型的对象。 Polymorphism, Dynamic Binding and Generic Programming When the method m(Object x) is executed, the argument x’s toString method is invoked. x may be an instance of GraduateStudent, Student, Person, or Object. Classes GraduateStudent, Student, Person, and Object have their own implementation of the toString method. Which implementation is used will be determined dynamically by the Java Virtual Machine at runtime. This capability is known as dynamic binding. Dynamic Binding Dynamic binding works as follows: Suppose an object o is an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass of Cn. That is, Cn is the most general class, and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p, the JVM searches the implementation for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an implementation is found, the search stops and the first-found implementation is invoked. Method Matching vs. Binding Matching a method signature and binding a method implementation are two issues. The compiler finds a matching method according to parameter type, number of parameters, and order of th
显示全部