多态概念
多态作用
代码实例:
Person父类
//父类子类、基类派生类、super类
public class Person {
final double heigh;
private int age;
private String name;
public Person() {
heigh=1.0;
}
public Person(int age) {
heigh=2.0;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void eat(){
System.out.println("eating....");
}
public void play(){
System.out.println("playing....");
}
}
man继承person类
public class Man extends Person{
@Override//表示下面的方法为重写的方法
public void eat() {
System.out.println("男人吃饭细嚼慢咽");
}
public void makeUp(){
System.out.println("我喜欢化妆");
}
}
woman继承person类
public class Woman extends Person {
@Override
public void eat() {
System.out.println("女人吃饭狼吞虎咽");
}
}
测试类
public class PersonTest {
public static void main(String[] args) {
method1();
method2();
eat(new Man());//Person person=new Man();//多态
eat(new Woman());//Person person=new Woman();
eat(new Person());
eat(new Zhong());
Man m1 = new Man();
Woman m2 = new Woman();
System.out.println(m1);//Object x=new Man();
System.out.println(m2);//Object x=new Woman();
Person m4 =new LittleMan();
m4.eat();
Object m5= new LittleMan();
// m5.eat();
}
public static void eat(Person person){
person.eat();
}
/*public static void eat(Man man){
man.eat();
}
public static void eat(Woman woman){
woman.eat();
}*/
private static void method2() {
Person m1=new Man();//父类的引用指向子类的实例,当调用重写方法时,调用的是子类重写后的方法
m1.eat();
m1.play();
//编译的时候看左边(Person),运行的时候看右边(Man)
// m1.makeUp(); 调用不了Person内没有直接报错
Person w1=new Woman();
w1.eat();
}
private static void method1() {
Person p1 = new Person();
Man m1 = new Man();
Woman w1 = new Woman();
p1.eat();
m1.eat();
w1.eat();
//调用结果
/*eating....
男人吃饭细嚼慢咽
女人吃饭狼吞虎咽*/
}
}
测试类二
public class PersonTest2 {
public static void main(String[] args) {
method1();
}
private static void method1() {
//编译看person中是否有方法
Person m1=new Man();//向上转型,从子类到父类
Man m2=(Man) m1;//向下转型,把父类类型转化为子类类型
m2.makeUp();
//编译通过,运行
// Man m3=(Man) new Person();//运行出错
// m3.makeUp();
// Woman w1=new Man();
// Person p1=new Man();
// Woman w2=(Woman) p1;
// w2.eat();
// String s=new Person();
}