I am confused about the code below. This code is written by someone else and I am currently studying the code to make more sense of how parameter-passing works in Java.
Does code #1
addKeyListener((KeyListener)new TAdapter());
and code #2
addKeyListener(new TAdapter());
mean the same thing and perform the same thing assuming TAdapter is a class that extends the KeyAdapter class? I also notice I do not necessarily have to explicitly cast the TAdapter object as a KeyListener even though from the method description I read in Eclipse the method takes in a KeyListener object. Why is this possible?
I did a quick search on the KeyAdapter class from Java docs and apparently the KeyAdapter class implements the KeyListener interface.
So am I safe to assume that one of the way Java works in parameter passing is that the method can accept an instance of a class that inherits from a certain class that implements an interface of the same name listed in the method description? If this is so, why is this also possible?
P.S. On a side note, I do not understand why the programmer name the class TAdapter, what does the T stand for? I also notice this type of class naming in other source code, but I never understood this supposed convention.
Well, yes, it is true that “the method can accept an instance of a class that inherits from a certain class that implements an interface”.
More generally, a class that
implementsan interface can be said to be a subclass of that interface in terms of polymorphism, and any parameter or variable can be assigned an instance of any subclass of its declared class.As for why that class is named
TAdapter, I’m afraid I can’t answer. It’s not any generally used convention, at least. 🙂