How to use a concrete class method created from an interface?

1

In the Lawyer class, I've implemented all of the properties and methods of the IPessoaFisica Interface, and a few other methods and methods of the Lawyer class , such as Advocate () and Oab.

How do I access this method? Being that in creating the Advocate object I created it as TestMethod below:

public interface IPessoaFisica
{
    int PessoaId { get; set; }
    string Nome { get; set; }
    IEndereco Endereco { get; set; }
    IContato Contato { get; set; }
    string Cpf { get; set; }
    string Identidade { get; set; }
    char Sexo { get; set; }
}

//Classe Concreta
public class Advogado: IPessoaFisica
{
    public int PessoaId { get; set; }
    public string Nome { get; set; }
    public IEndereco Endereco { get; set; }
    public IContato Contato { get; set; }
    public char Sexo { get; set; }
    public string Identidade { get; set; }
    public string Cpf { get; set; }
    public string Oab { get; set; }

    public void Advogar()
    {
        //Fazer qualquer coisa
    }
}

public void TestMethod1()
{
    IPessoaFisica adv = new Advogado();
    adv.Cpf = "111.111.111-11"; //OK
    adv.Nome = "José da Silva"; //OK
    adv.Advogar(); //ERRO - IPessoaFisica não contém definição de Advogar.
               // Método esta na classe concreta Advogado,e não está declarado na interface IPessoaFisica.
}
    
asked by anonymous 18.09.2016 / 20:12

1 answer

5

Although your object is built as Advogado it is declared as IPessoaFisica which makes only the methods of the IPessoaFiscia interface accessible. To access the Advogar method you will need to make one of the following changes:

Option 1- Declare the advocate method in the interface IPessoaFisica

Option 2 - Change the variable type adv to Advogado :

public void TestMethod1()
{
    Advogado adv = new Advogado();
    adv.Cpf = "111.111.111-11";
    adv.Nome = "José da Silva";
    adv.Advogar();
}

Interfaces are used to allow constructing common object abstractions and thus to use polymorphism. This is only useful when polymorphic methods are declared in the interface because there you can operate on variables declared with the type of interfaces. When you need to use specific methods that can not be abstracted and consequently can not be declared on the interfaces it is necessary to operate on variables with the concrete implementation type to allow access to your concrete methods.

    
18.09.2016 / 20:21