When should I normally use the interface?

Asked 2 years ago, Updated 2 years ago, 81 views

I understand the difference between an interface and an abstract class, but when should I use the interface correctly?

interface java

2022-09-21 20:18

1 Answers

When you implement an interface in a class, the interface that is implemented acts like the type used to refer to an instance of that class. Therefore, the interface that the class implements must represent what the client can do with the instance of that instance. It is not appropriate to use the interface for any other purpose. For example, a constant interface. Such an interface consists only of a static final field that does not have a method and has a constant value that you provide to the outside. In a class that uses such constants, you implement the interface to use constants without naming the classes before the constant field name.

public interface PhysicalConstants{
    //Number of Avogadro
    static final double AVOGARDROS_NUMBER = 6.02214199e23;
    //Voltzmann constant
    static final double BOLTZMANN_CONSTANT= 1.3806503e-23;
    //electron mass
    static final double ELECTRON_MASS = 9.10938188e-31;
}

Constant interface patterns use interfaces poorly. The constants used internally by the class belong to a detailed implementation of the class, but implementing a constant interface exposes those detailed implementations to the class' external api. It is not important to the class user that the class implements a constant interface. But it can confuse them. And what's worse, that implementation represents the fulfillment of promises going forward. What I mean is that future distributions no longer need to use that constant, so even if you change the class, you still need to implement that constant interface to maintain binary compatibility. If a non-final class implements a constant interface, the namespace of all subclasses in that class will be reduced. (Because names such as constant field names in constant interfaces are not allowed)

Then, when you want to provide a constant to the outside, it is better to create a constant utility class.

package com.effectivejava.science;

public class PhysicalConstants{
    Prevent creation of private PhysicalConstants(){}//instances

    public static final double AVOGARDROS_NUMBER = 6.02214199e23;
    public static final double BOLTZMANN_CONSTANT= 1.3806503e-23;
    public static final double ELECTRON_MASS     = 9.10938188e-31;
}

It's better to make it this way.


2022-09-21 20:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.