Java Interface: Implement Animal interface with a method bark()

Java Interface: Exercise-2 with Solution

Write a Java program to create a Animal interface with a method called bark() that takes no arguments and returns void. Create a Dog class that implements Animal and overrides speak() to print "Dog is barking".

Sample Solution:

Java Code:

// Animal.java
// Interface Animal

public interface Animal {
    void bark();

// Dog.java
// Class Dog

public class Dog implements Animal {
    public void bark() {
        System.out.println("Dog is barking!");
// Main.java
// Class Main

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();

Sample Output:

Dog is barking! 


This exercise defines an interface called "Animal" with a method bark() that takes no arguments and returns void. We then define a class called "Dog" that implements the "Animal" interface and overrides the bark() method to print "Dog is barking" to the console.

In the Main class we create an instance of the "Dog" class and call the bark() method, which should print 'Dog is barking' to the console.

Flowchart of Interface Animal:

Flowchart: Interface Animal

Flowchart of Class Dog:

Flowchart: Class Dog

Flowchart of Class Main:

Flowchart: Class Main

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Shape with the getArea() method, implement the Shape interface.
Next: Implement the Flyable interface.

What is the difficulty level of this exercise?

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

How do I remove repeated elements from ArrayList?

If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:

Set<String> set = new HashSet<>(yourList);

Of course, this destroys the ordering of the elements in the ArrayList.

Ref: https://bit.ly/3bYIjNC


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook