Assuming following case:
Logger logger = new ConsoleLogger();
Shouldn't that be
ConsoleLogger logger = new ConsoleLogger()
Why is the name on the left side different to the name on the right side?
Assuming following case:
Logger logger = new ConsoleLogger();
Shouldn't that be
ConsoleLogger logger = new ConsoleLogger()
Why is the name on the left side different to the name on the right side?
In Java it's called Polymorphism.
Logger logger = new ConsoleLogger();
Logger
is the type that logger
accepts. It may be any object of type Logger
or a subclass of it. By that reason you see a different type.
In practice, this means that you can define something like this:
Animal animals = new Dog(); // Dog extends Animal
Animal animals = new Cat(); // Cat extends Animal
...
Logger logger = new ConsoleLogger();
is probably a field declaration (it could also be a local variable declaration, if found within the body of a method, but the types suggest it's at the class level).
Here Logger
is the type of the variable logger
. new ConsoleLogger()
is the value we initialize logger
with. ConsoleLogger
is almost certainly a subclass of Logger
(or a class implementing Logger
if that is an interface).
Simply speaking you want the variable to be the most generic type that still has all the required methods. In this case you want the code that uses the logger
variable to not know that it's logging to the console. You just want it to use the methods that the Logger
class (or interface) provides without any regard what the specific implementation is.