Polymorphism in Java

Asked

Viewed 329 times

7

Example:

// Super classe: Carro
abstract public class Carro {
     String nome;

     public void andar(){
        // anda
     }
 }

// Sub classe: Fusca
public class Fusca extends Carro {

     public void andar(){
        super.andar();
        // Faz algo a mais
     }
}

// Main
public class Principal { 
    public static void main(String[] args) {

        Carro fusca1 = new Fusca(); // 1
        Fusca fusca2 = new Fusca(); // 2
    }
}

I wanted to know what is the difference between instance 1 and instance 2? And one more question, which arose, which access modifier should I use in the superclass?

  • 3

    Reference: http://answall.com/a/25968/7210

1 answer

8


Instance 1 accepts any object that is of the Car class or a child class of the Car class, so it accepts objects Carro, Fusca and a Ferrari extending the class Carro. And according to @Jorge B.’s comment, this instance will not accept commands from a daughter class, as the super class has not defined these commands.

Instance 2 accepts only objects Fusca, taking the example of Ferrari, this would not be accepted as it is not a daughter class of Fusca.

If you are going to make use of interfaces, do it this way:

public interface InterfaceExemplo {
  public void metodo();
}

public class A implements InterfaceExemplo {
  public void metodo() {
    //Corpo do metodo
  }
}

public class Main {
  public static void main(String[] args) {
    InterfaceExemplo Obj1 = new A(); //Aceito
  }
}

Browser other questions tagged

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