一、多态
子类和父类汇总起来就可以成为多态。
例如:父类A有一个public权限的方法method(),子类A1,A2对该方法进行重写;
A a= new A1();A a= new A2(); A a= new A();
a是调用子类A1、A2、父类A的method方法。
向上转型:父类引用指向子类对象
父类 Person 子类 Student
可以这样定义 Person p = new Student();
to string 类型(重写父类方法)
例子:
public class TestToString(){
public static void main(String[]args)
{
Dog d = new Dog();
System.out.println("d:="+d);
}
}
复制代码
class Dog(){
public String toString()
{
return"I'm a hot dog!";
}
}
复制代码
二、练习题
1.在包a中编写一个类Father,具有属性:年龄(私有)、姓名(公有);具有功能:工作(公有)、开车(公有)。
在包a中编写一个子类Son,具有属性:年龄(受保护的)、姓名;具有功能:玩(私有)、学习(公有)。 最后在包b中编写主类Test,在主类的main方法中测试类Father与类Son。
1.public class Father {
private int age;
public String name;
public void work(){
System.out.println(2);
}
public void drive(){
}
}
复制代码
2.public class Son {
private int age;
public String name;
private void paly(){
System.out.println(23);
}
public void study(){
}
}
复制代码
3.public class Test {
public static void main(String[] args) {
Father father = new Father();
father.work();
Son son = new Son();
}
}
复制代码
2.在其main方法中分别创建Aodi和Benchi的对象,并测试对象的特性
public class E {
public static void main(String[] args) {
Audio audio = new Audio();
audio.variableSpeed();
Benchi benchi =new Benchi();
benchi.variableSpeed();
}
}
复制代码