封装(encapsulation)
隐藏对象的属性和实现细节,仅对外公开接口,控制在程序中属性的读取和修改的访问级别
继承
package com.gem.java.day2;
public class Animal {
privateString name;
privateint age;
publicString getName() {
returnname;
}
publicvoid setName(String name) {
this.name= name;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age= age;
}
publicvoid show(){
System.out.println("------show(父)-----");
}
publicAnimal(){
System.out.println("------Animal(无参)-----");
}
publicAnimal(String name,int age){
System.out.println("------Animal(有参)-----");
this.name=name;
this.age=age;
}
publicstatic void main(String args[]){
Animalanimal=new Animal();
animal.show();
}
}
多态
package com.gem.java.day2;
public class Cat extends Animal{
inti;
privateString type;
publicString getType() {
returntype;
}
publicvoid setType(String type) {
this.type= type;
}
publicvoid show(){
System.out.println("------show(子)-----");
}
publicCat(){
//this和super不能同时出现在构造方法当中
//每一个有参或无参的构造,默认一个行代码就是super(隐含的)
//super的作用域指向父类(调用父类当中的属性和方法)
super();
// this();
System.out.println("------Cat(无参)-----");
}
publicCat(String type){
System.out.println("------Cat(有参)-----");
this.type=type;
}
/**
* @param args
*/
publicstatic void main(String[] args) {
//TODO Auto-generated method stub
// Catcat=new Cat();
// cat.setName("猫");
// cat.setAge(3);
// cat.setType("波斯猫");
// cat.show();
// System.out.println(cat.getName());
Animal animal=new Cat();
//1.必须有继承,多态一定是父子之间产生的关系
//2.有覆盖(override)
//3.父类引用指向子类对象
//编译时多态(按照父类编译) 运行时多态 (按照子类运行)
animal.show();
}
}