incompatible types can not be converted to

0

I'm starting to study java and after watching the creation of some objects I decided to try to create my own.

  

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: deodorant.Desclasse can not be converted to deodorant.Deodorant       at deodorant.Deodorant.main (Deodorant.java:4) "

There is no other line with an error, and my object looks very similar to the example. Can someone help me?

package desodorante;

public class Desodorante {
    public static void main(String[] args) {
    Desodorante c1 = new Desoclasse(); //essa é a linha com erro

package desodorante; //aqui a classe
public class Desoclasse {
    String cor;
    String perfume;
    int carga;
    int peso;
    boolean levantado;
    
asked by anonymous 22.07.2017 / 23:45

1 answer

1

The problem is the incompatibility of Types, as Exception itself is saying:

  

Incompatible types: Deodorant. Deodorant can not be converted to deodorant. Deodorant

Let's look at why this occurs:

Desodorante c1 = new Desoclasse();
  • The variable c1 was declared to be Type Desodorante ,
  • You have created a Type Object Desoclasse by doing new Desoclasse() ,
  • Finally, you have tried to assign the c1 (which is of type Desodorante ) to the created object that is of type Desoclasse !
  •   

    This is why the error occurred: Desoclasse not is-a Desodorante .

    To solve this, we can make Desoclasse pass to be-a Desodorante , like this:

    public class Desoclasse extends Desodorante {...}
    

    Another way to solve is to make the variable c1 be able to receive a% object Desoclasse , which we can do as follows:

    Desoclasse c1 = new Desoclasse();
    

    As all objects are -a Object ( java.lang.Object ), we can also do this:

    Object c1 = new Desoclasse();
    

    The concepts presented here have to do with Polymorphism and Inheritance , as you study them you will understand this better.

        
    23.07.2017 / 00:42