Instantiating an Object with a different reference

Asked

Viewed 1,174 times

5

I’m learning polymorphism in Java, but I’m having some doubts.

public class Animal {

    int numPatas;

    public void fazerBarulho() {

        // Código do Método
    }

    public void comportamento() {

        // Código do Método
    }
}

public class Felino extends Animal {

    public void comportamento() {

        // Aqui o método é reescrito,
        // pois um Felino tem um
        // comportamento próprio
        // de um felino.

    }
}

public class Gato extends Felino {

    // O Gato é um Felino e ao mesmo
    // tempo é um animal.
    // Então ele tem um numero de patas e,
    // o comportamento de um felino.

    public void fazerBarulho() {

        // Mas gato tem um barulho único
        // de um gato.
        // Pois um gato não faz o mesmo
        // barulho de um leão.

    }
}

This concept of polymorphism I understand. But what happens when we do that?

Animal umAnimal  = new Gato();

2 answers

6


When a Cat is instantiated in the Animal, this animal will have all the properties of the cat as you can see in the example below.

But he will remain an animal and any additional method of the Cat or Cat will not be available in the same (without casting).

The code below is in Gist.

Main java.

public class Principal {
    public static void main(String[] args) {
        Animal bicho = new Gato();
        System.out.println("Num patas do bicho " + bicho.numPatas);
        bicho.fazerBarulho();
        //bicho.gatoMia(); <- não pode porque não está definido no Animal
        Gato gato = (Gato) bicho;
        gato.gatoMia();
    }
}

Exit:

On the paws of bug 4

MEOW

MEOW

Java animal.

public class Animal {
    int numPatas;

    public void fazerBarulho() {

        // Código do Método
    }

    public void comportamento() {

        // Código do Método
    }
}

Felino.java.

public class Felino extends Animal{
       public Felino(){
           this.numPatas = 4;
       }
}

Gato.

public class Gato extends Felino{
    @Override
    public void fazerBarulho(){
        System.out.println("MIAU");
    }
    public void gatoMia(){
        this.fazerBarulho();
    }
}

Observing

In this case, the recommended would be that the Animal is an interface as represented below:

public interface Animal {
    public int getNumPatas();
    public void fazerBarulho();
    public void comportamento();
}

And then the other classes would implement such an interface:

public class Felino implements Animal {
    int numPatas;
    public Felino() {
        this.numPatas = 4;
    }

    @Override
    public int getNumPatas() {
        return numPatas;
    }

    @Override
    public void fazerBarulho() {
        throw new UnsupportedOperationException("Não disponível.");
    }

    @Override
    public void comportamento() {
        throw new UnsupportedOperationException("Não disponível.");
    }
}

Note that Cat does not need to be modified (with these recommendations and the only change in Main Class is bicho.getNumPatas() in place of bicho.numPatas.

  • 1

    Thank you Kyllopardiun! about the interface I will see you in the next chapter of my book. But in the example above, there is still inheritance in the cat class, when you implement Animal to the cat class?

  • No, everything happens according to what is set at the time to call if do Felino felino = (Felino) bicho; will have the felino.numPatas and felino.fazerBarulho() but you won’t have the gatoMia(). And to instantiate Animal bicho = new Felino(); the method fazerBarulho() will do nothing.

  • Ah now I think I understood understood :) In the inheritance, a class Cat that extends Feline, will have all the methods and attributes of Feline, now instantiate Animal Bug = new Feline(); all methods of the class Animal that were superimposed on Feline, will run like Felino, but if Felino has methods that do not exist in Animal, will not exist in Animal if there is no explicit casting?

  • 1

    Exactly that. =)

  • Ahhh man after I read what I wrote I thought I was going crazy, cracked laughing ahsuahsuahusah Brigadão :) !!!!!!!!

4

When you do:

Animal umAnimal  = new Gato();

It means that the variable umAnimal, type Animal, will behave like a Cat.

If you create a method walk in class Animal, and then overwrite that method walk in class Pussycat, when you call an Imal.walk(); at runtime the method written in the class will be invoked Pussycat and not what was written in the class Animal, because what is in memory (what was instantiated) is a Cat object.

If you want to better understand and clearly concepts of inheritance, rewriting and polymorphism, I advise you to click here.

  • Thank you Electus! I downloaded the workbook and I know it will help a lot. Unfortunately I cannot yet mark your reply as useful. I need more home time on stackoverflow :)

  • No problem. More important than having the answer marked as correct is being able to help. Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.