计算机可以有多个品牌,如联想、惠普等。Java利用计算机编写一个显示多态的程序,不同品牌的计算机启动时,输出该计算机所属品牌。
时间: 2024-03-17 13:42:31 浏览: 8
可以通过编写一个计算机类,在该类中定义一个启动方法,该方法根据计算机所属品牌输出不同的信息。具体实现如下:
```java
public class Computer {
private String brand;
public Computer(String brand) {
this.brand = brand;
}
public void start() {
System.out.println("This computer is from " + brand);
}
}
```
然后,在主函数中创建不同品牌的计算机对象,并调用启动方法即可,示例代码如下:
```java
public static void main(String[] args) {
Computer lenovo = new Computer("Lenovo");
lenovo.start();
Computer hp = new Computer("HP");
hp.start();
}
```
输出结果为:
```
This computer is from Lenovo
This computer is from HP
```
相关问题
Java用面向对象的思想实现一个多态程序
好的,我可以给您提供一个简单的示例程序,用Java面向对象的思想实现多态。
假设我们有一个动物类 Animal,它有一个方法 sound(),用于发出声音。我们还有两个子类 Cat 和 Dog,它们都继承自 Animal 类,并重写了 sound() 方法。
下面是示例代码:
```java
class Animal{
public void sound(){}
}
class Cat extends Animal{
public void sound(){
System.out.println("Meow");
}
}
class Dog extends Animal{
public void sound(){
System.out.println("Woof");
}
}
public class Main{
public static void makeSound(Animal animal){
animal.sound();
}
public static void main(String[] args){
Cat cat = new Cat();
Dog dog = new Dog();
makeSound(cat); // 输出 Meow
makeSound(dog); // 输出 Woof
}
}
```
在这个示例程序中,我们定义了一个 makeSound() 函数,它接受一个 Animal 对象作为参数,并调用它的 sound() 方法。
当我们传递一个 Cat 对象给 makeSound() 函数时,它会调用 Cat 类中重写的 sound() 方法,输出 "Meow";当我们传递一个 Dog 对象时,它会调用 Dog 类中的 sound() 方法,输出 "Woof"。
这就是多态的实现,不同的对象调用相同的方法,但会产生不同的行为。
java用面对对象的思想实现一个多态程序
好的,我可以为您提供一个简单的Java多态程序示例,如下:
```java
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("The cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();
animal1.makeSound();
animal2.makeSound();
animal3.makeSound();
}
}
```
在这个示例中,我们定义了一个Animal类,以及两个它的子类:Dog和Cat。每个类都包含一个makeSound()方法,但是每个子类都覆盖了父类方法以提供不同的实现。在主方法中,我们创建了一个Animal对象,以及两个它的子类对象,并且调用了它们的makeSound()方法。由于Java的多态性,每个对象根据实际类型调用相应的方法,所以输出的不同。