Marquake
Marquake

Reputation: 191

implement class or import class java

Internally for Java what is better, or what is optimal, or What is the standard: implement a class with constants or using dot notation?

Example:

Option 1:

import com.myproject.Constantes;

public class myClass {
    myClass() {
        System.out.println("Math: " + Constantes.PI);
    }
}

Option 2:

import com.myproject.Constantes;

public class myClass implements Constantes {

    myClass() {
        System.out.println("Math: " + PI);
    }
}

Which is better and why? MVJ use, resources, speed?

Upvotes: 9

Views: 7611

Answers (6)

Cuong Le
Cuong Le

Reputation: 121

I think OPTION 1 should be used to avoid mistaking another PI defined internally in the current class.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533530

Often clarity is more important than performance and this is no exception.

Option 1 is preferred to option 2 as the latter implies that myClass is a Constantes which doesn't make sense.

Since Java 5.0 you have another option which may be better.

import static com.myproject.Constantes.PI;
// OR
import static com.myproject.Constantes.*;

public class MyClass{
  MyClass(){
       System.out.println("Math: " + PI);
  }
}

Upvotes: 1

LuigiEdlCarno
LuigiEdlCarno

Reputation: 2415

Option 1 should be used, because this will definetly use the constant defined in the imported class.

If you had a local variable called PI in myClass, Option 2 would you that variable, instead of the one in the imported class.

Upvotes: 3

SJuan76
SJuan76

Reputation: 24885

implements (an interface, not a class) says that myClass must honour the contract specified by Constantes (usually with some method specifications that must be implemented in your class).

Please, check about Object Oriented Programming (Programación Orientada a Objetos) concepts before getting into the particularities of any given language.

Upvotes: 1

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

You're doing two different things here. In the first fragment you're just writing code that happens to reference stuff in the Constantes class/interface and thus needs to be import'ed whereas in the second fragment, you're stating the your code must conform to the Constantes interface, i.e. implementing any and all methods therein.

Cheers,

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074415

If Constantes is purely a collection of constants (as the name implies) and doesn't define functionality that you need to expose in myClass, then A) It shouldn't be an interface, and B) You shouldn't implement/extend it. Import it and use it as in Option 1.

Upvotes: 9

Related Questions