Is there a difference in how the polymorphism in Java and C # is applied?

4

I'm studying the concepts of OOP and it gave me a question.

In Java I believe I can access all methods and attributes declared as public in a subclass even when I use a superclass type variable to reference this subclass.

But in C # I can not access subclass methods when I assign your reference to a superclass?

Is there a difference between languages? If so, why, if the concept of POO is theoretically 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.
    
asked by anonymous 31.05.2017 / 19:09

2 answers

5
  

In java I believe I can access all methods and attributes declared as public in a subclass even when I use a superclass type variable to reference this subclass.

No, you can not.

It does not make sense to access members of a subtype in a higher type. In neither language will this work.

This, in fact, has nothing to do with polymorphism. It would be interesting to read the publication below

31.05.2017 / 19:20
7

Jbueno's answer has already said that it does not work, but there is a solution. I'll kick in more or less what the class will look like:

using static System.Console;
using System;

public class Program {
    public static void Main() {
        ContaPoupanca poupanca = new ContaPoupanca();
        poupanca.CalculaInvestimento();
        Conta conta = new ContaPoupanca();
        conta.CalculaInvestimento();
    }
}

public class Conta {
    public virtual void CalculaInvestimento() { throw new NotImplementedException(); }
}
public class ContaPoupanca : Conta {
    public override void CalculaInvestimento() { WriteLine("ok"); }
}

See running on .NET Fiddle . And at Coding Ground . Also put it on GitHub for future reference .

If that's what you need, it's another story.

    
31.05.2017 / 20:18