面向对象——多态+重写

多态就是很简单的意思,一瓶酒,五粮液、剑南春、二锅头,都是酒

以酒为父类,五粮液、剑南春、二锅头为子类,酒为延伸出去三种酒

这种就是多态

多态指向子类,

1:又有继承条件,就是extends

2:子类重写父类方法,也就是覆写,为什么覆写,其实就是每瓶酒都有

不同的特点,烈,甜,苦,那你想要甜的时候,酒又不能每次喝的时候

全部都能体现出不一样的风格那么就要重写他的方法单独写一个烈的二锅头

的方法,然后单独调用,等同于酒柜子里单独拿二锅头

3:父类指向子类,就是   父类名 方法名=new 子类名

 

代码示例:

teacher:父类

package 面向对象.多态;

public class teacher {
public void bc(){
System.out.println("父类多态");
}
public void abc(int a)
{

System.out.println("父类方法"+a);
}
}

shtduent1:子类

package 面向对象.多态;

public class student1 extends teacher{
public void abc(int a)
{
System.out.println("student1方法"+a);
}
}

student:子类

package 面向对象.多态;

public class student extends teacher{
public void ab()
{
System.out.println("子类多态");
}
public void abc(int a)
{
System.out.println("student方法"+a);
}
}

多态调用:

package 面向对象.多态;

public class 多态 {
public static void main(String[] args) {
student a=new student();
teacher b=new teacher();
teacher c=new student1();
teacher d=new student();
//因为student类继承父类所以他可以调用子类和父类的方法
a.ab();
a.bc();
System.out.println();
//因为只是单纯teacher类所以调用父类只有父类方法
b.bc();
System.out.println();
//多态是什么意思呢,就是多态是方法名相同的情况下,那么 父类 类型名=new 子类
//父类指向子类,有继承条件,子类重写父类方法,父类指向子类类型
//多态是方法的多态,不是属性是多态的
c.abc(1);
d.abc(2);
b.abc(3);
}
}
 
posted @ 2021-12-25 20:33  道者顺心也  阅读(57)  评论(0)    收藏  举报