继承多态的简单代码

 

 

 

class Employee{

}

class Leader extends Employee{

}

public class App{

       public static void main(String[] args){

               Employee e=new Employee();

               Leader l=new Leader();

               System.out.println(e instanceof  Employee);

               System.out.println(l  instanceof  Employee);

               System.out.println(e instanceof  Leader);

               System.out.println(l  instanceof  Leader);

       }

}

转载于:https://www.cnblogs.com/wangyufei123/p/7977827.html

下面是一个简单的Java代码示例,演示了如何使用继承多态和封装: ```java // 定义一个Animal类 class Animal { private String name; private int age; public Animal(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void eat() { System.out.println(name + " is eating."); } } // 定义一个Dog类,继承自Animal类 class Dog extends Animal { public Dog(String name, int age) { super(name, age); } // 重写eat方法 @Override public void eat() { System.out.println(getName() + " is eating bones."); } // 新增方法 public void bark() { System.out.println("Woof! Woof!"); } } // 定义一个Cat类,继承自Animal类 class Cat extends Animal { public Cat(String name, int age) { super(name, age); } // 重写eat方法 @Override public void eat() { System.out.println(getName() + " is eating fish."); } // 新增方法 public void meow() { System.out.println("Meow! Meow!"); } } // 测试类 public class Main { public static void main(String[] args) { Animal animal1 = new Animal("Animal", 5); animal1.eat(); // 输出:Animal is eating. Dog dog1 = new Dog("Dog", 3); dog1.eat(); // 输出:Dog is eating bones. dog1.bark(); // 输出:Woof! Woof! Cat cat1 = new Cat("Cat", 2); cat1.eat(); // 输出:Cat is eating fish. cat1.meow(); // 输出:Meow! Meow! // 使用多态 Animal animal2 = new Dog("Poodle", 1); animal2.eat(); // 输出:Poodle is eating bones. // animal2.bark(); // 编译错误,Animal类没有bark方法 Animal animal3 = new Cat("Siamese", 2); animal3.eat(); // 输出:Siamese is eating fish. // animal3.meow(); // 编译错误,Animal类没有meow方法 } } ``` 在上面的代码中,我们定义了一个Animal类,它有私有的name和age属性,以及公有的getName、getAge和eat方法。然后我们定义了一个Dog类和一个Cat类,它们都继承自Animal类,并且分别重写了eat方法,并新增了各自的方法bark和meow。 在测试类Main中,我们分别创建了一个Animal、一个Dog和一个Cat对象,并调用了它们的方法。然后我们使用多态,将一个Dog对象和一个Cat对象分别赋值给Animal类型的变量,然后调用它们的eat方法。可以看到,它们分别调用了Dog和Cat类中重写的eat方法,而不是Animal类中的eat方法。此外,由于Animal类没有bark和meow方法,我们无法在animal2和animal3对象上调用这些方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值