I dont understand why is that
for example:
class Test
{
public void someMethod()
{
}
}
and then
Test test = new Test();
why is neccesary to write the type of the variable, so if you see that the variable assigns that custom class, i think that is some overflow writing).
ps: this is java, and i am new to it, so sorry if a quiestion is stupid, but i dont understand this moment
You’re declaring the type of the variable (reference), as distinct to the type of the object.
e.g. your variable type could be
Test, or it could be a supertype (Object), or an interface thatTestimplements. Which one you choose depends on how your clients should refer to the initialised object. e.g. should they know it’s a particular type, or is it sufficent (or desirable) that they only know it will implement a given interface, or subset of features.A better example would be:
in which your client code only knows that it’s dealing with an Animal. i.e. it can (say) call a method
.eat(), but it won’t know that aDogeats differently to aFish.Note that some languages (e.g. Scala) will perform type inference. That is, you don’t have to declare the variable type, but rather the compiler will determine what type it should be from your subsequent usage of the variable. The resultant code is still statically typed, but the compiler does more work for you.