0

I'm new to JAVA coming from C++. What is the difference between assigning an implementation to an interface variable vs the actual implementation variable?

Foo f = new FooImpl();

versus

FooImpl f = new FooImpl();

  • Kind of. So if you use the interface variable, you don't get access to any of the methods defined in the implementation class if they aren't in the Interface? – NewDeveloper Jan 21 '21 at 16:09
  • @NewDeveloper correct. If you don't need the methods from a specific implementation, using the more general interface allows you to call the method with other implementations too. – Andy Turner Jan 21 '21 at 16:20
  • Basically, yes. But it also means that with `f` declared as `Foo`, your code is guaranteed to rely only on behavior promised by the `Foo` interface. If you later decide that a different `Foo` implementation, say, a `FooImpl3`, is a better fit, you just change the declaration to `Foo f = new FooImpl3();` and everything else still works. – Kevin Anderson Jan 21 '21 at 16:31

0 Answers0