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 {
@Override
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();
dog.bark();
}
}
Sample Output:
Dog is barking!
Explanation:
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 of Class Dog:

Flowchart of 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?
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); yourList.clear(); yourList.addAll(set);
Of course, this destroys the ordering of the elements in the ArrayList.
Ref: https://bit.ly/3bYIjNC
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
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