Polymorphism in Java

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 the difference between instance 1 and instance 2? And one more question, which arose, which access modifier should I use in the superclass?

    
asked by anonymous 13.01.2015 / 16:59

1 answer

8

Instance 1 accepts any object that is in the class Car or a child class of it, so it accepts objects Carro , Fusca , and Ferrari that extends the Carro class. And according to @Jorge B.'s comment, this instance will not accept commands from a child class, since superclass did not define those 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 are going to use interfaces, do 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
  }
}
    
13.01.2015 / 17:02