4
I’m studying the concepts of POO and generated me a doubt.
In Java I believe I can access all methods and attributes declared as public in a subclass even when using a superclass type variable to reference this subclass.
However, in C# I cannot access the subclass methods when assigning your reference to a super class?
Is there such a difference between languages? If so, why, if the concept of POO theoretically is the same for any programming language?
Example:
ContaPoupanca poupanca = new ContaPoupanca();
poupanca.CalculaInvestimento();
Conta conta = new ContaPoupanca();
conta.CalculaInvestimento(); // Não consigo acessar esse método através da variável conta.
If the method is unique to the subtype, will not work even in java.
– user28595
This has nothing to do with the fact that every private Java method is equivalent to the virtual C method#?
– Jefferson Quesado
@Jeffersonquesado ?!?!?!!?! :)
– Maniero
@bigown, I may be getting confused... but come on; in the section 10.5.3 the documentation speaks of The implementation of a non-virtual method is invariant (like, don’t look
vtable
), whereas In Contrast, the implementation of a virtual method can be superseded by derived classes. (like, lookvtable
); in Java, every private method suffers this superseded mentioned, even the bytecode to call the nonprivate instance method has as mnemonicinvokeVirtual
, saying that will always check thevtable
.– Jefferson Quesado
This is not the case because if it is private, there is no reason to look elsewhere. But I think I now understand what you mean. In Java every public method is virtual by default, and in C# is not virtual by default. There it is. But in essence it does not change the behavior, only the default is another.
– Maniero