Good day,
I am new to JAVA'm learning this language and what I have learned it seems a fantastic language. My question is in relation to the following:
Suppose I have a class like this:
public class Person{
private String firstName;
private String lastName;
private int age;
private String entireName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEntireName() {
return entireName;
}
public void setEntireName(String entireName) {
this.entireName = entireName;
}
public static void Main(String args[]){
Person person = new Person();
person.setFirstName("Jhon");
person.setLastName("Adams");
person.setAge(20);
//Atention this line
person.setEntireName(person.getFirstName()+person.getLastName());
}
}
The language allows me to do this: person.setEntireName(person.getFirstName()+person.getLastName());
and it works fine however I would like to know how is best to do this, how it behaves at the object level and how high or low the performance.
Thank you ..
What you do is perfectly valid, but not very logical. Why not just drop the setEntireName() since it just combines two existing fields?
public String getEntireName() {
return firstName + " " + lastname;
}
This is valid. There is no performance difference, becasue JIT compiler optimize this code if needed (simply replace method with fields access).
Typically it is easier to eliminate the entireName property and its setter, and use the getter to perform the concatenation like so:
public String getEntireName() {
return firstName + " " + lastName;
}
This is also easier to maintain than updating entireName every time firstName or lastName is changed.
Related
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 1 year ago.
Recently I was going through the concept of Encapsulation in Java. I was wondering if making data variables private along with public setter methods really make sense in simple POJO class? Please refer below POJO:
public class Employee{
private String id;
private String name;
private String department;
private int age;
public Employee(){
}
public Employee(String id, String name, String department, int age){
this.id = id;
this.name = name;
this.department = department;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I mean why am I making the name variable private when I can anyway change it using the setter method?
In the general case, it'll be the very basic
public void setName(String name) {
this.name = name;
}
Where it's identical to just doing employee.name = "william hammond". But imagine a case where you'd like to do implement something like a private String normalize(string username) method where you maybe make it all lower case, check for a valid name or prevent unicode entries. If you make name public initially you'll have users doing employee.name = "whatever they want :) 123" and you'll lose the ability to enforce that constraint.
Also see Why use getters and setters/accessors?
Using getters/setters is just considered good practice, but it can often be overkill - like in your example.
If you have methods that mutate the variable before setting, then it's nice to have getters/setters for the basic fields as well to maintain consistent code style.
Here's a good article on it:
https://dzone.com/articles/getter-setter-use-or-not-use-0
Let's have an example:
public class Example {
private String firstName;
private String lastName;
public Example(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
This class has 3 properties (firstName, lastName, fullName), but only two fields (firstName, lastName). It makes sense, because a full name can be retrieved by combining first and last name.
However, I've noticed that I call getFullName() a lot of times in my program, but I almost never call getFirstName() and getLastName(). This slows down my program, because I need to create a new string each time getFullName() is called. So, I've refactored my code to have a better performance:
public class Example {
private String fullName;
public Example(String firstName, String lastName) {
this.fullName = firstName + " " + lastName;
}
public String getFirstName() {
return fullName.split(" ")[0];
}
public String getLastName() {
return fullName.split(" ")[1];
}
public String getFullName() {
return fullName;
}
}
Now my code works faster when calling getFullName(), but slower when calling getFirstName() and getLastName(), however It's exactly what I needed. From outside the class, nothing really've changed.
As you can see by the given example, fields describe how your class uses the computer's memory, but not necessarily which properties your class has. This is why fields should be considered an implementation detail and therefore be private to a class.
So within this class, I need to create a Equals method that will check to determine if the two objects have the same name. I tried creating the two objects within the class and just initialize it with "" for the constructor, but it gave an error on the created objects
Person.Java
public class Person
{
String firstName = "";
String lastName = "";
String age = "";
public Person (String firstName, String lastName, String age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(String age){
this.age = age;
}
public String toString(){
return firstName + " " + lastName + ", " + age + " years old";
}
}
Here is my driver, so basically I need a method that sees both have the same name and prints out a message saying that they have the same name. My lab states it has to be in the class NOT the driver, which is why I'm lost considering I could easily make an if/else statement within the driver.
public class PersonDriver
{
public static void main(String[] args)
{
Person p1 = new Person("John","Doe", "42");
Person p2 = new Person("John","Doe", "43");
System.out.println(p1);
System.out.println(p2);
}
}
I've created a Person class, and a class that inherits from it, the Professor class. Now, I've declared my setters private in the Person class and Professor class. I want the constructors to set the variables, by calling the setters and performing validation. Is what I've done correct? If not, what can I do to correct it?
Person Class:
public class Person {
private String firstName;
private String lastName;
public Person(String firstname,String lastname) throws InvalidDataException
{
setFirstName(firstname);
setLastName(lastname);
}
public String getFirstName() {
return firstName;
}
private void setFirstName(String firstName) throws InvalidDataException {
if ( firstName == null || firstName.length() < 1) {
throw new InvalidDataException("Person Must have First Name");}
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
private void setLastName(String lastName) throws InvalidDataException {
if ( lastName == null || lastName.length() < 1) {
throw new InvalidDataException("Person Must have Last Name");}
this.lastName = lastName;
}
Professor class
public class Professor extends Person {
private String professorID;
public Professor(String professorID,String firstname, String lastname) throws InvalidDataException {
super(firstname, lastname);
// TODO Auto-generated constructor stub
this.setID(professorID);
}
private void setID(String professorID) throws InvalidDataException{
if ( professorID == null ||professorID.length() < 1) {
throw new InvalidDataException("Person Must have ID");}
this.professorID = professorID;
}
public String getID()
{
return this.professorID;
}
public void printData()
{
System.out.println("Professor ID: " + this.getID() + " First Name: " + this.getFirstName() + " Last Name: " + this.getLastName());
}
}
Considering that your "setters" mainly check Strings for being neither null nor empty, you might have a static or utility method doing just that, and call it in the constructor (and/or public setters) before you assign to the class member.
public class Person {
protected void check( String s, String msg ){
if( s == null ||s.length < 1) {
throw new InvalidDataException(msg);
}
}
public Person(String firstname,String lastname) throws InvalidDataException{
check( firstname, "Person's first name missing" );
check( lastname, "Person's last name missing" );
this.firstname = firstname;
this.lastname = lastname;
}
public void setFirstname( String firstname ){
check( firstname, "Person's first name missing" );
this.firstname = firstname;
}
}
But a bean shouldn't need guards like this. If there's a GUI, the GUI should do the validation, passing only correct values to object construction.
It is a bad practice to declare setters as private . because setters goal is to call them outside that class from the class instance. If you really want to fill your class properties with the constructor you may create a private functions that will build up your class.
** ps: if your class attributes are easy to fill you may fill them in your constructor .you dont need any support functions.
The best way would be to set the Person class members protected instead of private.
Anyway, setters and getters are supposed to be public in OOD.
This question already has answers here:
Constructors vs Factory Methods [closed]
(10 answers)
Closed 8 years ago.
I want to create a static class which works like enumeration, but with string values.
Which of the following ways is the safest to extract a full instance of created class?
public class Name
{
public static final Name MY_NAME = new Name("Chris", "Doe");
public String firstName;
public String lastName;
public Name(firstname, lastname)
{
this.firstName = firstname;
this.lastName = lastname;
}
}
OR
public class Name
{
public String firstName;
public String lastName;
public Name(firstname, lastname)
{
this.firstName = firstname;
this.lastName = lastname;
}
public static Name myName()
{
return new Name("Chris", "Doe");
}
}
Safest? I'm not sure what you mean by that.
As far as best-practices go, the second is potentially wasteful, as it will allocate a new instance of Name every time myName() is invoked. The other uses a constant, so it conserves more memory.
All of which is relatively trivial in a small application.
If you're trying to have your class emulate an enum, the constant is certainly the way to go, as the values of an enum are initialized only once.
Just in case you don't know what an enum actually is, here would be a sample implementation of your class as one:
public enum Name {
MY_NAME ("Chris", "Doe");
private final String firstName;
private final String lastName;
private Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
... and you could then simply refer to Name.MY_NAME.
I would like to go with the first one, because the first one comprises of static final Name MY_NAME whereas in the second case a new Name instance would be returned everytime you call the myName() method resulting in wastage of memory. So, better go with the first one.
So, to extract a full-instance of a created class, you should go with the first one.
Also,talking about enum----in which you hold constant values, your static field final Name MY_NAME instance will serve the purpose, you should stick to the first-declaration----thereby supporting your need of enum as well as not wasting memory!
go after first method,
create your public static instances of class, make your class final so it cant be extended, and make constructor private, so it cannot be instantiate outside of your class
flaw with second method is, your static method myName each time creates new instance of Name which is unnecessary
If you only need one object instance with the fixed values why bother having member variables at all?
This way is thread safe regardless of how you use the object.
public class Name
{
public String getFirstName() {
return "Chris"
}
public String getFirstName() {
return "Doe"
}
}
If you must have member variables then:
public class Name
{
public final String firstName = "Chris"
public final String lastName = "Doe"
}
But as others have suggested just use the enum:
public enum Name {
me("Chris", "Doe");
private String firstName;
private String lastName;
Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
How do I create a class that has different lengths of arguments?
public static void main(String[] args) {
group g1 = new group("Redskins");
group g2 = new group("Zack", "Mills", 21);
group g3 = new group("John","Smith",20);
group g4 = new group("Fred","Fonsi",44);
group g5 = new group("Jeb","Bush",26);
System.out.println(g1.getName());
}
}
I want to be able to display the team name (redskins) and then each member after that using one method.
I've tried using two methods and got that to work, but can't get one.
I was thinking about possibly using an array but not sure if that would work.
Thanks for any help.
I have three classes the main, student, and group.
I need the group class to display the group name and then figure out how to display the students information underneath. The only thing, is that my assignment is vague about whether I can use two methods or one.
public class student {
String firstName;
String lastName;
int age;
student(String informedFirstName, String informedLastName, int informedAge){
firstName = informedFirstName;
lastName = informedLastName;
age = informedAge;
}
String getName()
{
return "Name = " + firstName + " " + lastName + ", " + "Age = " + age;
}
}
public class Team{
String name;
Set<Player> players;
public Team(String name){
this.name = name;
}
public void addPlayer(Player p){
players.add(p);
}
}
public class Player{
String name;
etc
}
EDIT for revised question:
Ok, Im going to show a lot here. Heres what a proper Java versio of what you want for student.
public class Student {
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/*
* Use:
* Student s = new Student(Bill, Nye, 57);
* System.out.println(s.toString());
*/
#Override
public String toString() {
return "First Name: " + firstName + ", Last Name: " + lastName + ", Age: " + age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The Things to take away from this.
1) Capitalize the first letter of class names! (Student)
2) note the class variables are private (look here for a tutorial Java Class Accessibility) and have getters and setter to control access outside the class.
3) I dont say "getName()" and return name and age. This doesnt make sense. Instead i make it so when you go toString() it shows all the relevant information.
4) Java is an object oriented language which means the classes that model data are supposed (to some extent) model appropriately to the way they are used in real life. This makes it more intuitive to people reading your code.
5) if your Group class (note the capital!) needs to contain many Students use a LIST such as an ArrayList. Arrays would make no sense because you dont know how many Students are going to be in each Group. A SET like i used above is similar to a list but only allows ONE of each item. For simplicity use a list though
6) the THIS operator refers to class (object) variables. In the constructor this.firstName refers to the firstName within the Class (object...an instance of the class) whereas just firstName would refer to the variable in the contructor and not alter the class variable.
use the constructor for that
class group {
String fname,lname;
group(String fname ){
this.fname=fname;
}
group(String fname,String lname){
this.fname=fname;
this.lname=lname;
}
group(String fname,String lname,int age){
this.fname=fname;
this.lname=lname;
this.age=age;
}
public String getName(){
return fname+lname+age;
}
}