Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 433
Marquake Avatar asked Oct 29 '12 10:10

Marquake


3 Answers

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.

like image 76
T.J. Crowder Avatar answered Oct 11 '22 09:10

T.J. Crowder


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

like image 25
Cuong Le Avatar answered Oct 11 '22 07:10

Cuong Le


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.

like image 20
LuigiEdlCarno Avatar answered Oct 11 '22 09:10

LuigiEdlCarno