Interface
All interface classes are by default Public
and Abstract
, and do not contain any completed methods.
Interface should implement (complete the body of a method) when all the abstract methods are inherited from the superclass (abstract class).
The actual use of interface will be structuring (setting or mandating to set off rules).
An example of a Java program with an interface
The following is an example of an interface in a Java program:
package MyFirstPackage; interface sample_abs2 { void abstr_method (); void abstr_method1(); } abstract class sample_abs3 implements sample_abs2 { abstract void abstr_method2 (); void abstr_method2A(){ System.out.println("Abstact class abstr_method2A"); } } class Interface extends sample_abs3 {//implements is a keyword used to complete the //Interface Class public void abstr_method () { System.out.println("Interface abstr_method implementation"); } public void abstr_method1 () { System.out.println("Interface abstr_method1 implementation"); } public void abstr_method2 () { System.out.println("Abstact class abstr_method2 implementation"); } public static void main(String[] args) { System.out.println("interface class demo"); Interface objI = new Interface(); objI.abstr_method(); objI.abstr_method1(); objI.abstr_method2(); objI.abstr_method2A(); } }
The output will be as follows:
interface class demo Interface abstr_method implementation Interface abstr_method1 implementation Abstact class abstr_method2 implementation Abstact class abstr_method2A
Abstract classes compared with interfaces
For more details on abstract classes versus interfaces, visit http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html.
The this keyword
The this
is a Java keyword that is used as an alternate for creating an instance for a nonstatic variable or method within a same class.
An example for the this
keyword is as follows:
package MyFirstPackage; class ThisKeyword{ int id; String name; //Constructor method ThisKeyword(int id, String name){ //constructor variable and instance variable names are same this.id = id; this.name = name; } void display(){ System.out.println(id + " " + name); } public static void main(String args[]){ ThisKeyword objThis1 = new ThisKeyword(1234,"John"); ThisKeyword objThis2 = new ThisKeyword(2456,"Smith"); objThis1.display(); objThis2.display(); } }
The output for the preceding code will be as follows:
1234 John 2456 Smith