因为经常将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(); } }
原文地址:http://blog.csdn.net/feixia586/article/details/26201921