Java Tutorials
How to easily Convert String to Integer in JAVA
There are two ways to convert String to Integer in Java, String to Integer using...
An Interface in Java programming is defined as an abstract type used to specify the behavior of a class. A Java interface contains static constants and abstract methods. A class can implement multiple interfaces. In Java, interfaces are declared using the interface keyword. All methods in the interface are implicitly public and abstract.
Syntax for Declaring Interface
interface { //methods }
To use an interface in your class, append the keyword "implements" after your class name followed by the interface name.
Example for Implementing Interface
class Dog implements Pet
interface RidableAnimal extends Animal, Vehicle
Click here if the video is not accessible
To understand the concept of Java Interface better, let see an example. The class "Media Player" has two subclasses: CD player and DVD player. Each having its unique implementation method to play music.
Another class "Combo drive" is inheriting both CD and DVD (see image below). Which play method should it inherit? This may cause serious design issues. And hence, Java does not allow multiple inheritance.
Now let's take another example of Dog.
Suppose you have a requirement where class "dog" inheriting class "animal" and "Pet" (see image below). But you cannot extend two classes in Java. So what would you do? The solution is Interface.
The rulebook for interface says,
Class Dog can extend to class "Animal" and implement interface as "Pet".
Step 1) Copy following code into an editor.
interface Pet{ public void test(); } class Dog implements Pet{ public void test(){ System.out.println("Interface Method Implemented"); } public static void main(String args[]){ Pet p = new Dog(); p.test(); } }
Step 2) Save , Compile & Run the code. Observe the Output.
| |
---|---|
In class, you can instantiate variable and create an object. | In an interface, you can't instantiate variable and create an object. |
Class can contain concrete(with implementation) methods | The interface cannot contain concrete(with implementation) methods |
The access specifiers used with classes are private, protected and public. | In Interface only one specifier is used- Public. |
Summary:
There are two ways to convert String to Integer in Java, String to Integer using...
Java String contains() method The Java String contains() method is used to check whether the...
In this tutorial, we will study programs to To convert a character to String To convert a String to...
You can use JavaScript code in two ways. You can either include the JavaScript code internally within...
What is = in JavaScript? Equal to (=) is an assignment operator, which sets the variable on the...
What is this Keyword in Java? this keyword in Java is a reference variable that refers to the...