OCAJP | Interfaces
Use Interfaces
Declaring an interface : When you create an interface, that means you are defining a prototype of class, that what a class can do. In other words we can say interface is pre-declaration of class.
Rules for defining an interface :
1. All methods of an interface are implicitly public & abstract whether you declare or not.
2. All variables of interface must be public, static, or final i.e., we can declare only constants but not variables.
3. Interface methods can’t be static.
4. Because interface methods are abstract , so it can’t be final,strictfp or native.
5. Interface can extend one or more other interfaces.
6. Interface can’t extend anything other than interface.
7. Interface can’t implement any class or other interface.
8. Interface must be declared with the keyword interface.
Some legal declaration of interface :
1. public abstract interface Bounceable { }
2. Modifier abstract is optional , interfaces are implicitly abstract whether you declare or not.
public abstract interface Bounceable { }
public interface Bounceable { }
Both are valid declarations
public abstract interface Bounceable { }
public interface Bounceable { }
Both are valid declarations
3. public modifier is required if you want the interface to have public rather than default access.
4. public and abstract modifier in method declaration is optional as methods are implicitly public & abstract in interface.
public interface Bounceable{
public interface Bounceable{
void bounce(); //no modifier
void setBounceFactor(int bf); //no modifier
void setBounceFactor(int bf); //no modifier
}
5. Following method declaration if declared within their own interfaces are legal and identical:
void bounce();
public void bounce();
public abstract void bounce();
abstract public void bounce();
void bounce();
public void bounce();
public abstract void bounce();
abstract public void bounce();
6. Following method declaration won’t compile.
final void bounce();
static void bounce();
private void bounce();
protected void bounce();
final void bounce();
static void bounce();
private void bounce();
protected void bounce();
Declaring Interface Constants :
You’re allowed to put constants in an interface.
They must be always public, static, final.
Need not to declare public static or final they are implicitly public static and final.
public int x = 1;
int x = 1;
static int x = 1;
static int x = 1;
final int x = 1;
public static int x = 1;
public final int x = 1;
static final int x = 1;
public static final int x = 1;
Without explicitly using the required modifier , all the following above declarations are valid and identical
public static int x = 1;
public final int x = 1;
static final int x = 1;
public static final int x = 1;
Without explicitly using the required modifier , all the following above declarations are valid and identical
nice !.
ReplyDeletepls visit for java updates @https://java4teachus.blogspot.com