标签:print tom 覆盖 ++ ring 隐式 程序猿 over java程序
由于常常将Java和C++面向对象编程的原则搞乱,所以这次把相关要点分别总结一下,本文主要总结Java面向对象编程。
面向对象编程的三大特性是:继承性(inheritance), 多态性(polymorphism)和封装性(encapsulation)。
[类修饰词列表] class 类名 [extends 父类名] [implements 借口列表名] { 类体 }
class Employee { public int workYear; public Employee() { workYear = 1; } } class Teacher extends Employee { public int classHour; public Teacher() { classHour = 10; } }
// correct Teacher tom = new Teacher(); Employee a = tom; Teacher b = (Teacher) a; // runtime error Employee a = new Employee(); Teacher b = (Teacher) a;
Teacher a = new Teacher(); Employee b = new Employee(); Employee c = a; System.out.println((b instanceof Teacher)); // false System.out.println((c instanceof Employee)); // true System.out.println((c instanceof Teacher)); // true
静态多态性是指在同一个类中同名方法在功能上的重载(overload)。
class Employee { public int workYear; public Employee() { workYear = 1; } public printInfo() { System.out.println("This employee has worked for " + workYear + " years."); } } class Teacher extends Employee { public int classHour; public Teacher() { classHour = 10; } public printInfo() { System.out.println("This employee has worked for " + workYear + " years."); System.out.println("This teacher has worked for " + classHour + " hours."); } } public class Main { public static void main(String[] args) { Employee a = new Teacher(); a.printInfo(); } }
标签:print tom 覆盖 ++ ring 隐式 程序猿 over java程序
原文地址:http://www.cnblogs.com/blfbuaa/p/6798489.html