Interface in Java
Interface in Java. In this Article i will explain what is an interface by stepping through the sample program below
In the sample program below, first I will create 2 interface class named “animalNoise, animalMamal ” .Then i will create a class call “doggy” and then implement the interface “animalNoise, animalMamal ” into the class doggy. Finally i will create another class call ” accessAnimal ” to access the created new object.
An interface in java can be explained as a blueprint of a class.
Interface animalNoise
- First i will create an Interface called ” animalNoise “
- This Interfaces will be implemented to the class doggy later.
package Animal; public interface animalNoise { public void makeNoise(); }
Interface animalMamal
- Create an Interface called ” animalMamal “
- This Interfaces will be implemented to the class doggy later.
package Animal; public interface animalMamal { public void mamalFeature(); }
class doggy
- As we know , a dog make noise, and a dog is a mamal
- Thus when create this new class doggy , i will implement both interface “animalNoise,animalMamal” into the class by using the “implements” keyword
package Animal; public class doggy implements animalNoise, animalMamal { String dogName; public void mamalFeature() { System.out.println("A dog is a mamal"); } public void makeNoise() { System.out.println("woof woof"); } }
class accessAnimal
- I will create a new doggy object call lucky
- Call the Method in the Lucky Object “makeNoise() /mamalFeature()”
package Animal; public class accessAnimal { public static void main(String[] args) { // TODO Auto-generated method stub doggy lucky= new doggy(); lucky.makeNoise(); lucky.mamalFeature(); } }
Check out Abstract in Java Here