您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,多态是通过继承、接口和方法重写实现的
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("The dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.sound(); // 输出 "The dog barks"
myAnimal = new Cat();
myAnimal.sound(); // 输出 "The cat meows"
}
}
interface Flyable {
void fly();
}
class Bird implements Flyable {
@Override
public void fly() {
System.out.println("The bird is flying");
}
}
class Airplane implements Flyable {
@Override
public void fly() {
System.out.println("The airplane is flying");
}
}
public class Main {
public static void main(String[] args) {
Flyable myFlyable = new Bird();
myFlyable.fly(); // 输出 "The bird is flying"
myFlyable = new Airplane();
myFlyable.fly(); // 输出 "The airplane is flying"
}
}
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.sound(); // 输出 "The dog barks"
}
}
总之,Java中的多态允许我们使用父类或接口类型的引用来操作子类对象,并在运行时根据实际类型调用相应的方法。这使得我们的代码更具扩展性和灵活性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。