Java Interface Statics.
Java Interface static methods and variables
- A static method is a method that is associated with the interface in which it is defined rather than with any object.
- Classes can NOT override static methods with their own implementation.
- An interface can contain constants which will be considered final and static,
- and which can be referred to directly
- through the interface name,
-
and also appear in any class that implements the interface.
Interface static method and variables example:
interface Scaleable { // this will automatically be static final public String DECIMALPATTERN="#"; // this will automaticly considered to be final public static enum Type {BIG, MEDIUM, SMALL}; public void setScale(Type size); public String getArea(); // This is a static method public static String getFormatted(double value) { DecimalFormat formatter = new DecimalFormat(DECIMALPATTERN); return formatter.format(value); } } class Rectangle implements Scaleable { private int width; private int height; @Override public void setScale(Type size) { switch (size) { case BIG: width = 500; height = 500; break; case MEDIUM: width = 300; height = 300; break; case SMALL: width = 200; height = 200; break; } } @Override public String getArea() { return Scaleable.getFormatted(width * height); } } class Circle implements Scaleable { private int radius; @Override public void setScale(Type size) { switch (size) { case BIG: radius = 500; break; case MEDIUM: radius = 300; break; case SMALL: radius = 200; break; } } @Override public String getArea() { return Scaleable.getFormatted(radius * radius * Math.PI); } } public class interfaceStaticApp { public static void main(String[] args) { Rectangle rect = new Rectangle(); rect.setScale(Scaleable.Type.BIG); System.out.println("Rectangle area = " + rect.getArea()); Circle circle = new Circle(); circle.setScale(Scaleable.Type.SMALL); System.out.println("Circle area = " + circle.getArea()); } }
The result of this is:Rectangle area = 250000 Circle area = 125664
© 2010 by Finnesand Data.
All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the
correctness in the pages or source codes.
The risk of using this web-site pages or any program
codes from this website is entirely at the individual user.