Declaring Interface Constants

Declaring Interface Constants

In this interface we are allowed to put a constants in an interface,it would be much easier for programmers to remember names like HIGH_GRAVITY, LOW_BOUNCE, and HIGH_BOUNCE as opposed to knowing the exact int values corresponding to each of those. we have a following code :

public final static int LOW_BOUNCE = 4;
public final static int HIGH_GRAVITY = 3;
That way, if a method takes the int values,
public void animateIt(int gravity, int bounceFactor) { }
then the code that calls animateIt() can substitute the constants wherever the
int values are expected, as follows:
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE);
  changes we\'ve made
to the Bounceable interface:
public interface Bounceable {
int LOW_GRAVITY = 1;
int LOW_BOUNCE = 4;
int HIGH_BOUNCE = 12;
void bounce();
Interface Implementation (Exam Objective 4.2) 59
void setBounceFactor(int bounceFactor);
void setGravity(int gravity);

By placing the constants right in the interface, any class that implements the interface
has direct access to the constants, just as if the class had inherited them. For example,
the following would be legal for a Bounceable implementation class:

class Ball implements Bounceable {
// Lots of exciting code goes here
public void bounce() {
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE); // MUCH easier this way
// Still more action-packed code goes here

We have a some Rules for the interface constraints :
  1. public
  2. static
  3. final

Date:2025-02-09 00:00:00

Post Your Answers

User Email:

User Name:

Related Java Subjective Links

Java Subjective interview questions and answers for experienced and fresher