Get startedGet started for free

Implementing abstract methods

You will change the Toyota and Mercedes classes to give each car its implementation for the horn sounding. For uniqueness, you will create a version of the method for sounding the horn in both the Toyota and Mercedes classes.

NOTE: An abstract method must be implemented when inherited from an Abstract class, within the subclass.

This exercise is part of the course

Introduction to Object-Oriented Programming in Java

View Course

Exercise instructions

  • Implement the soundHorn method in the Toyota class to print "sounds like a toyota".
  • Implement the soundHorn method inside the Mercedes class to print "sounds like a mercedes".
  • Inside the main method, call the soundHorn method on the myToyota instance and the soundHorn method on the myMercedes instance.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class Main {  

	static class Toyota extends Car {
    
        public Toyota() {
            super();
        }

        // Create soundHorn for Toyota
        ___ ___ ___() {
            System.out.println(___);
        }
    }

    static class Mercedes extends Car {

        public Mercedes() {
            super();
        }

        // Create soundHorn for Mercedes
        ___ ___ ___() {
            System.out.println(___);
        }
    }

    static abstract class Car {

        public Car() {

        }

        public abstract void soundHorn();

    }
    
    public static void main(String[] args) {
        Toyota myToyota = new Toyota();
        Mercedes myMercedes = new Mercedes();
        
        // Call "soundHorn" for myToyota and myMercedes
        ___.___;
        ___.___;
    }
    
}
Edit and Run Code