重载与重写
程序员文章站
2022-03-25 14:05:17
...
package polymorphic;
public class Test {
public static void main(String[] args) {
show(new Cat());
show(new Dog());
System.out.println("-------------");
Animal a = new Cat();
a.eat();
a.eat(3);
//a.work();
Cat b = (Cat)a;
b.sport();
Animal a2 = new Dog();
a2.eat();
//a.work();
Dog b2 = (Dog)a2;
b2.sport();
Work d = new Work();
d.work();
Work f = new Cat2();
f.work();
}
public static void show(Animal a) {
a.eat();
if(a instanceof Cat) {
Cat c = (Cat)a;
c.sport();
}else if (a instanceof Dog) {
Dog c = (Dog)a;
c.sport();
}
}
}
class Work{
public void work() {
System.out.println("Catch mice");
}
}
abstract class Animal{
public abstract void eat() ;
public void eat(int num) {
System.out.println("[重载1eat rice]");
for(int i = 0; i < num; i++)
System.out.println("[重载1eat rice]");
}
}
class Cat2 extends Work{
public void way() {
System.out.println("重写");
}
public void work() {
System.out.println("[重写 again]");
}
}
class Cat extends Animal{
//int num = 2;
//System.out.println("Hi, I am a Cat.");
public void eat() {
System.out.println("1eat fish");
}
public void sport() {
System.out.println("1can flow");
}
}
class Dog extends Animal{
//System.out.println("Hi, I am a Dog.");
public void eat() {
System.out.println("2eat beef");
}
public void sport() {
System.out.println("2can run");
}
}