Interface in Java

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

  1. First i will create an Interface called  ” animalNoise “
  2. This Interfaces will be implemented to the class doggy later.

 


package Animal;

public interface animalNoise {
	
	public void makeNoise();

}


 

Interface animalMamal

  1. Create an Interface called  ” animalMamal “
  2. This Interfaces will be implemented to the class doggy later.

 

package Animal;

public interface animalMamal {
	
	public void mamalFeature();

}


 

class doggy

 

  1. As we know , a dog make noise, and a dog is a mamal
  2. 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

 

  1. I will create a new doggy object call lucky
  2. 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

Leave a Comment

thirteen − one =