学习内容
1.多态
2.抽象类
多态
概述;
同一个对象,在不同的时刻表现出来的不同形式。
前提:要有继承或实现关系要有方法的重写要有父类引用指向子类队象。
多态的好处:
提高程序的扩展性,定义方法的时候,使用父类型作为参数,在使用的时候,使用具体的子类型参与操作。
多态的转型:
向上转型
向下转型
例如:
package com.hg.demo01;
public class demo01Extends {
public static void main(String[] args) {
Zi zi=new Zi();
zi.showNum();
zi.methodB();
}
}
package com.hg.demo01;
public class Fu {
int num=10;
public Fu() {
}
public Fu(int num) {
}
}
package com.hg.demo01;
public class Zi extends Fu {
int num=20;
public Zi() {
//super();
this(100);
System.out.println("我是子类的无参构造方法"); }
public Zi(int n) { System.out.println("我是子类的有参构造方法"+n);}
public void showNum(){
int num=30;
System.out.println(num);
System.out.println(this.num);
System.out.println(super.num);}
public void methodA() { System.out.println("AAA");}
public void methodB() {
methodA();
System.out.println("BBB");
}
}
抽象类
概述:
当我们在做子类共性功能抽取时,有些方法在父类中并没有具体的体现,这个时候就需要抽象类了。
抽象类的特点:
1.抽象类和抽象方法必须使用abstract关键字修饰
2.抽象类中不一定有抽象方法,有抽象方法的类一定是抽象类。
3.抽象类不能实例化
4.抽象类8的子类要么重写抽象类中的所有抽象方法要么是抽象类。
例如:
package com.hg.demo02;
public abstract class Animal {
public Animal() {
System.out.println("抽象父类中的构造方法");
}
public abstract void eat();
public abstract void food();
public void normalMehted() {
}
}
package com.hg.demo02;
public class Cat extends Animal {
public Cat(){
super();
System.out.println("子类中的构造方法");
}
@Override
public void eat(){
System.out.println("猫吃鱼");
}
public void food(){
}
}
package com.hg.demo02;
public class Demo02Main {
public static void main(String[] args) {
//Animal animal = new Animal();
Cat cat = new Cat();
cat.eat();
}
}
package com.hg.demo02;
public class MyAbstract {
public void sleep() {
}
}
例如2:
package com.hg.demo03;
public abstract class Animal {
public Animal() {
System.out.println("抽象父类中的构造方法");
}
public abstract void eat();
public abstract void sleep();
}
package com.hg.demo03;
public class demo03Main {
public static void main(String[] args) {
//Animal animal=new Animal();
//Dog dog = new Dog();
Dog2ha ha2=new Dog2ha();
ha2.eat();
ha2.sleep();
System.out.println("============");
DogGolden golden=new DogGolden();
golden.eat();
golden.sleep();
}
}
package com.hg.demo03;
public abstract class Dog extends Animal{
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
package com.hg.demo03;
public class Dog2ha extends Dog{
@Override
public void sleep() {
System.out.println("二哈 咬坏东西 睡觉");
}
}
package com.hg.demo03;
public class DogGolden extends Dog{
@Override
public void sleep() {
System.out.println("直接 站着睡觉");
}
}
运行结果如下:
2020080605041