incompatible types cannot be converted to

Asked

Viewed 1,014 times

0

I’m starting to study java and after observing the creation of some objects I decided to try to create my own. already in the first I found this error that I don’t know how to solve "incompatible types cannot be converted to", that stays on the line, and when I try to compile it appears like this.

Exception in thread "main" java.lang.Runtimeexception: Uncompilable source code - incompatible types: deodorant.Desoclasse cannot be converted to deodorant.Deodorant deodorant.Desodorante.main(Deodorant.java:4)"

There is no other line with error, and my object is very similar to the examples. someone can 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;
  • You may be trying to transform an object Desodorante in a kind Desoclasse and these classes have nothing to do with each other?

  • In short: Desodorante != Desoclasse

1 answer

1

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

incompatible types: deodorant. Deodorant cannot be converted to deodorant.Deodorant

Let’s analyze why this occurs:

Desodorante c1 = new Desoclasse();
  1. The variable c1 was declared to be of the Type Desodorante,
  2. You have created a Type Object Desoclasse in making new Desoclasse(),
  3. Finally, you tried to assign the variable c1 (who’s kind Desodorante) the Created Object that is of Type Desoclasse!

This is why the error occurred: Desoclasse nay is-one Desodorante.

To solve this, we can do Desoclasse move on to be-um Desodorante, thus:

public class Desoclasse extends Desodorante {...}

Another way to solve is to make the variable c1 be able to receive an Object Desoclasse, what we can do like this:

Desoclasse c1 = new Desoclasse();

Like all the Objects saint-one Object (java.lang.Object), we can also do so:

Object c1 = new Desoclasse();

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

  • Thank you very much Kra! for your help and kindness. I will continue my studies!

Browser other questions tagged

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