Polymorphism in Java

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 access modifier should I use in the superclass?

Author: Maniero, 2015-01-13

1 answers

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

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

If you go make use of interfaces, do it like this:

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
  }
}
 8
Author: mutlei, 2015-01-13 16:09:06