Who is the instance, who is the instance? Java

Asked

Viewed 50 times

0

Hello, I’m new with object-oriented programming and programming in general too, but in an example like the following:

public class Profissao{
      public void trabalhar(){
            //trabalho...
      }
}
public class Ferreiro extends Profissao{
      public void consertarEspada(){
            //conserta...
      }
}
public class Programa{
      public static void main(String args[]){
            
            Profissao x = new Ferreiro;
      }
}

I know the object is x, but is it the instance? If so, which class is it? Profession or Blacksmith?

And how can an object of the Profession type receive attributes or methods of the Blacksmith class in this case? If Blacksmith is a subclass of Profession.

Thanks in advance.

1 answer

4

I know the object is x, but is it the instance? If so, is the instance of what class? Professional or Blacksmith?

I wouldn’t say that x is the object, I would say x is a reference to the object. The object is the memory region that was allocated by the call new Ferreiro(), then a class instance Ferreiro.

And how a Professional object can receive attributes or methods of the Blacksmith class in this case? If Blacksmith is a subclass of Professional.

An object of the type Profissao cannot receive attributes or execute class methods Ferreiro, for your example using x it would be necessary to convert his type to Ferreiro

((Ferreiro)x).consertarEspada();

Following his example it would be complicated to use several classes derived from Profissao if each of them has a specific method, it would be more efficient if the class Ferreiro overwriting the method trabalhar()

public class Ferreiro extends Profissao{
      @Override
      public void trabalhar(){
            //conserta...
      }
}

So just calling x.trabalhar() it would perform its work function, regardless of what type of object x is referencing at the moment.

Browser other questions tagged

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