Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class best practice

Tags:

If I have a customer class with an overloaded constructor (default and one with params) what is the proper way to set the class members in the Overloaded constructor? Using "this" references or using the setter methods?

Just wasn't sure what the proper method was.

public class Customer {  private String firstName; private String lastName; private int age;  public Customer() {}  //This Way public Customer(String firstName, String lastName, int age) {     this.firstName = firstName;     this.lastName = lastName;     this.age = age; }  // Or this way?   public Customer(String firstName, String lastName, int age) {     setFirstName(firstName);      setLastName(lastName);     setAge(age); }    /**  * @return the firstName  */ public String getFirstName() {     return firstName; }  /**  * @param firstName the firstName to set  */ public void setFirstName(String firstName) {     this.firstName = firstName; }  /**  * @return the lastName  */ public String getLastName() {     return lastName; }  /**  * @param lastName the lastName to set  */ public void setLastName(String lastName) {     this.lastName = lastName; }  /**  * @return the age  */ public int getAge() {     return age; }  /**  * @param age the age to set  */ public void setAge(int age) {     this.age = age; } 

}

like image 592
scarpacci Avatar asked Sep 07 '12 20:09

scarpacci


People also ask

What are OOP practices?

Object-oriented programming aims to implement real-world entities like inheritance, abstraction, polymorphism, and encapsulation in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

How do you use OOPs?

Object Oriented Programming (OOP) is a software design pattern that allows you to think about problems in terms of objects and their interactions. OOP is typically done with classes or with prototypes. Most languages that implement OOP (e.g., Java, C++, Ruby, Python) use class-based inheritance.


1 Answers

The first one (using this.) is probably safer and more straightforward. Consider if a future subclass overrode the setter methods - this could cause very unexpected behavior.

If your class is final, this is irrelevant and it's a wash.

like image 100
Joe K Avatar answered Sep 30 '22 19:09

Joe K