封装隐藏了类的内部实现机制,能够在不影响使用的状况下改变类的内部结构,同时也保护了数据。对外界而已它的内部细节是隐藏的,暴露给外界的只是它的访问方法。ide
public class Student { public Student(String name, Integer age) { this.name = name; this.age = age; } private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
getter方法禁止返回可变对象的引用,可变对象引用会破坏封装(下面演示错误的使用封装方法)this
public class Student { public Student(Date birthday) { this.birthday = birthday; } private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } class Main{ public static void main(String[] args) { Student student = new Student(new Date()); System.out.println("student对象的Date:"+student.getBirthday());//student对象的Date:Tue Dec 11 10:50:50 CST 2018 Date birthday = student.getBirthday(); birthday.setTime(888888888); System.out.println("student对象的Date:"+student.getBirthday());//student对象的Date:Sun Jan 11 14:54:48 CST 1970 } }
经过继承建立的新类称为“子类”或“派生类”,被继承的类称为“基类”、“父类”或“超类”。继承的过程,就是从通常到特殊的过程。继承概念的实现方式有二类:实现继承与接口继承。实现继承是指直接使用基类的属性和方法而无需额外编码的能力;接口继承是指仅使用属性和方法的名称、可是子类必须提供实现的能力;编码
public class Student extends People { } class People{ void sayHello(){ System.out.println("Hello Word"); } } class Main{ public static void main(String[] args) { Student student = new Student(); student.sayHello(); } }
一个对象变量能够指向多种实际类型的现象被成为多态;在运行时可以自动选择调用那个方法被称为动态绑定.code
public class Student extends People { @Override void sayHello(){ System.out.println("I am a Student"); } void studentHello(){ System.out.println("It is student Say"); } } class Teacher extends People{ } class People{ void sayHello(){ System.out.println("Hello Word"); } } class Main{ public static void main(String[] args) { People people1 = new Teacher(); People people2 = new Student(); people1.sayHello(); people2.sayHello(); ((Student) people2).studentHello(); } }
要实现多态必须存在继承关系(student和teacher都继承people)对象
子类须要将父类的方法重写(继承已经默认重写),若是重写了父类方法则会使用重写方法继承
须要将子类的引用赋值给父类,这样父类变量就能够调用非子类特有方法接口
父类引用不能够赋值给子类变量,若是必须须要;能够使用强制类型转换,强制类型转换会暂时忽略对象的实际类型,使用对象的所有功能get
Student student = (Student) new People();