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; }
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With