w3resource

Java: Abstract Instrument Class with Glockenspiel and Violin Subclasses

Java Abstract Class: Exercise-9 with Solution

Write a Java program to create an abstract class Instrument with abstract methods play() and tune(). Create subclasses for Glockenspiel and Violin that extend the Instrument class and implement the respective methods to play and tune each instrument.

Sample Solution:

Java Code:

//Instrument.java
abstract class Instrument {
  public abstract void play();

  public abstract void tune();
}

//Glockenspiel.java
class Glockenspiel extends Instrument {
  @Override
  public void play() {
    System.out.println("Glockenspiel: Playing the notes on the metal bars.");
  }

  @Override
  public void tune() {
    System.out.println("Glockenspiel: Tuning the metal bars to the correct pitch.");
  }
}
//Violin.java
class Violin extends Instrument {
  @Override
  public void play() {
    System.out.println("Violin: Playing the strings with a bow or fingers.");
  }

  @Override
  public void tune() {
    System.out.println("Violin: Tuning the strings to the correct pitch.");
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Instrument glockenspiel = new Glockenspiel();
    Instrument violin = new Violin();

    glockenspiel.play();
    glockenspiel.tune();

    violin.play();
    violin.tune();
  }
}

Sample Output:

Glockenspiel: Playing the notes on the metal bars.
Glockenspiel: Tuning the metal bars to the correct pitch.
Violin: Playing the strings with a bow or fingers.
Violin: Tuning the strings to the correct pitch.

Explanation:

In the above exercise -

  • The abstract class "Instrument" has two abstract methods: play() and tune(). The subclasses Glockenspiel and Violin extend the Instrument class and provide their own implementations for these abstract methods.
  • The "Glockenspiel" class describes how a glockenspiel plays the notes on the metal bars and tunes them to the correct pitch, while the "Violin" class describes how a violin plays the strings with a bow or fingers and tunes the strings to the correct pitch.
  • In the main method, we create instances of Glockenspiel and Violin, and then call the play() and tune() methods on each object to demonstrate how each instrument plays and tunes.

Flowchart:

Flowchart: Instrument Java
Flowchart: Glockenspiel Java
Flowchart: Violin Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Abstract Person Class with Athlete and LazyPerson Subclasses.
Next: Abstract Shape2D Class with Rectangle and Circle Subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.