[Java] The difference between declaring variables with interfaces and implementing class declarations

The difference between declaring variables with interfaces and implementing class declarations

The difference is in accessible methods and fields
When declaring a variable with an interface and creating an object with an implementing class,Only methods and fields declared in the interface can be accessed, without access to other methods and fields defined in the implementing class. This means that any code that uses the variable is guaranteed to only have access to the methods and fields defined in the interface, making the code more abstract and generic.

  • (Similar to inheritance and polymorphism, if a parent class declares a variable and refers to a subclass object, then the variable can only access method fields in the parent class)

Conversely, if you declare and create a variable using the same implementing class, you can access all methods and fields defined in that implementing class. This enables direct manipulation of data and functionality in the implementing class, but also makes the code more specific and dependent on the implementing class.

Therefore, declaring variables with an interface and creating objects with an implementing class can make the code more abstract and generic , while declaring variables with an implementing class allows more direct manipulation of the data and functionality of that implementing class . Which one to choose depends on your specific needs and design goals.

Guess you like

Origin blog.csdn.net/hhb442/article/details/129332546