完全不知道怎么办,太可恶了

img


完全读不懂,太绕了,怎么写都报错,根本就是伪命题,怎么会这样

我来写,确实有些绕,但按题目的要求也是可以写出来的,你看看我写的是否符合题目的要求,有帮助的话采纳一下哦!我想令你迷惑的是,在哪个类中创建一个SoundMachine对象吧!因为他没写什么类,但根据后面说,创建了一个我们就可以推断出,他应该在测试类中比较合理。

img

Test.java

package Music;

public class Test {
    public static void main(String[] args) {
        SoundMachine sou = new SoundMachine();
        Violin s1 = new Violin();
        Piano s2 = new Piano();
        sou.play(s1);
        sou.play(s2);
    }
}

// Sound接口
interface Sound {
    void makeSound();
}

// SoundMachine类
class SoundMachine {
    public SoundMachine() {
    }
    void play(Sound sound){
        sound.makeSound();
    }
}

// 小提琴类
class Violin implements Sound{
    @Override
    public void makeSound() {
        System.out.println("小提琴的声音");
    }
}

//钢琴类
class Piano implements Sound{
    @Override
    public void makeSound() {
        System.out.println("钢琴的声音");
    }
}
interface Sound {
  public void makeSound();
}

class SoundMachine{
  public void play(Sound sound) {
    sound.makeSound();
  }
}

class Piano implements Sound{
  public void makeSound(){
    System.out.println("钢琴的声音");
  }
}

class Violin implements Sound{
  public void makeSound(){
    System.out.println("小提琴的声音");
  }
}

public class Main{
  public static void main(String[] args) {
    SoundMachine machine = new SoundMachine();
    Violin violin = new Violin();
    Piano piano = new Piano();
    machine.play(violin);
    machine.play(piano);
  }
}

建议题主可以自己先动动手哦,把接口,实现,方法重写这些知识先掌握了。这是java的基础知识,把基础打牢。

看看吧,大概就是这样的,不懂的再问

img


public interface Sound {
    public void makeSound();
}

public class SoundMachine {
    public void play( Sound sound){
        sound.makeSound();
    }
}
public class PianoSound implements Sound{
    @Override
    public void makeSound() {
        System.out.println("钢琴的声音");
    }
}


public class  ViolinSound implements Sound{

    @Override
    public void makeSound() {
        System.out.println("小提琴的声音");
    }
}


public class Main {
    public static void main(String[] args) {
        PianoSound pianoSound =new PianoSound();
        ViolinSound violinSound =new ViolinSound();
        SoundMachine soundMachine =new SoundMachine();
        soundMachine.play(pianoSound);
        soundMachine.play(violinSound);
    }
}


我给你写

package com.example.demo003.test;

interface Sound {
    void makeSound();
}

class XiaoTiqin implements Sound {
    @Override
    public void makeSound() {
        System.out.println("小提琴的声音");
    }
}

class Gangqin implements Sound {
    @Override
    public void makeSound() {
        System.out.println("钢琴的声音");
    }
}


public class SoundMachine {
    void play(Sound sound) {
        sound.makeSound();
    }

    public static void main(String[] args) {
        final Sound xiaoTiqin = new XiaoTiqin();
        final Sound gangqin = new Gangqin();
        final SoundMachine soundMachine = new SoundMachine();
        soundMachine.play(xiaoTiqin);
        soundMachine.play(gangqin);
    }
}