Set Variables by Java Constructor

Asked

Viewed 77 times

2

It is certain to "set" the variables passing by parameter directly in the constructor, equal to this code?

public class Retangulo extends FiguraGeometrica{

  private double largura;
  private double altura;

  public Retangulo(double altura, double largura){
   this.altura = altura;
   this.largura = largura;
  }
  public double obterArea(){
  return largura * altura;
  }
  public double obterPerimetro(){
   return 2 * largura + 2 * altura;
  }
}

Or so?:

  public Retangulo(Retangulo x){
  this.altura = x.altura;
  this.largura = x.largura;
 }

Or should I do a procedure for each variable?

  • Good question. But try to give a new one in the second option and think about how other constructors are used and pq

  • 1

    Related: https://answall.com/q/73530/112052

1 answer

3


Yes is right and desirable. Especially if they determine the valid state of the object.

This is the case of the first example, in it are "requests" all values for the object to be created in a valid state. It makes no sense to create a rectangular object that does not have the dimensions of its sides defined.

It is also ideal that these fields cannot be changed after the creation of the object.
A Rectangle is immutable. With other dimensions it is no longer that Rectangle, but another. Then a new one should be created.

The second example does not make sense, because it will not be possible to build the object, since it needs one to build it.

If he’s an alternative builder, with the intention of allowing his cloning, it doesn’t make sense. Being Rectangular immutable there is no need to have clones.
Analogous to String, it would be like having two strings with the same content in the same program. Of course you can, but for me, it makes no sense to give the object that prerogative.

  • Thank you very much !

  • @ramaral blz! I will remove the comment

  • Taking advantage of the dialogue, is it recommended to have a constructor that receives a "y" object to transform it into an "x"? Or such a situation would be more convenient to leave in a method?

  • 1

    @Walterfelipe. If it refers to creating an object of the same type, the use of a constructor is the most usual form. I can’t tell you if it’s the most convenient.

Browser other questions tagged

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