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;
}
}
Related
Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are
Abstraction
Encapsulation
Suppose we have an Employee class:
package com.highmark.productConfig.types;
public class Employee {
private String firstName;
private String middleName;
private String lastName;
public void getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
// Similarly for lastName
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
}
UPDATE : Is this usage right with the workerclass?
public class getNames() {
private String firstName;
private String middleName;
private String lastName;
//Constructor
public String getNames() {
Scanner input = new Scanner();
// output message to insert name part
String firstName = input.ReadLine();
String middleName = input.ReadLine();
String lastName = input.ReadLine();
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setMiddleName(middleName);
emp.setLastName(lastName);
}
}
Please try to explain the flaw in understanding if any.
Yes, you are correct on one thing for sure. Getters are Setters are a way to ensure the principle of Encapsulation in Object Oriented Programming languages like Java.
When you have a private member in your class, then its scope gets restricted to that particular class itself, but you may want to provide getters and/or setters to make that member accessible to classes outside your class.
Suppose you have a member like this,
private String firstName;
then this is your getter for this member,
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
but this is not,
public String getFirstName() {
Scanner user_input = new Scanner(System.in);
firstName = user_input.next( );
return firstName;
}
because "getter" is just a term used to get the value of a member which is private. The sole purpose of a getter method is just to get the original value of a member.
In the latter method, the purpose is absolutely different. You are trying to get the first name as input, so technically it cannot be called a "getter" in any way.
Hope this clears your doubt.
Actually i am implementing one program in which i am retrieving information from database and i am setting that info to One Object using setters and i just want to print that Object parameters without using system.out.println(object.getHeadCount());
I just want like if i am giving system.out.println(object); so using this code it should print data in Json format or any other readable format.
How to do it.Because my object is containing 30 fields so it is very hectic to write 30 getters to print data.
You have to override toString()
Normal way
class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString(){
return this.firstName + " " + this.lastName;
}
}
Using Apache Commons
class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString(){
return new ToStringBuilder(this)
.append("firstName", firstName)
.append("lastName", lastName)
.toString();
}
}
Using Google Guava
class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString(){
return MoreObjects.toStringHelper(this)
.add("firstName", firstName)
.add("lastName", lastName)
.toString();
}
}
You simply have to override the toString() method of the class, read about it in java doc for Object class. Most IDE support it's automatic generation for all the fields of your class or for a number of them. Just for example:
class User {
private String name;
private String surname;
User(String name, String surname)
{
this.name = name;
this.surname = surname;
}
#Override
public String toString()
{
return this.name+" "+this.surname;
}
}
You should override toString() method. if you are using eclipse then you can try right-click within the editor, you'll find it under Source -> Generate toString()
To make a toString method you can simply just add one like so.
public String toString(){
return "" + getValue();
}
The toString method is a part of
java.lang.Object
So it is implemented in every class.
I want to know if my implementation of the builder object has disadvantages compared to the builder object implementation I see on most site's. I know it's overkill to implement a builder object for a class with only 2 fields, but these are just examples and meant to be small.
My implementation:
public class User {
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
private User(){}
public static class Builder{
private final User user;
public Builder(){
user = new User();
}
public Builder firstname(String firstname){
user.firstname = firstname;
return this;
}
public Builder lastname(String lastname){
user.lastname = lastname;
return this;
}
public User build(){
return user;
}
}
}
Builder object as found on the internet (example1 example2):
public class User {
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
private User(Builder builder){
this.firstname = builder.firstname;
this.lastname = builder.lastname;
}
public static class Builder{
private String firstname;
private String lastname;
public Builder firstname(String firstname){
this.firstname = firstname;
return this;
}
public Builder lastname(String lastname){
this.lastname = lastname;
return this;
}
public User build(){
return new User(this);
}
}
}
The second implementations seems cumbersome, cause the builder needs to have exactly the same field as the object it will be building (read: writing the same code twice).
It also seems more naturally (to me) that the builder creates the new User and populates its fields, instead off calling the constructor of the User with it's own instance.
Both examples can be tested with:
public static void main(String[] args) {
User u = new User.Builder().firstname("Tom").lastname("Jonckheere").Build();
System.out.println(u.getFirstname());
System.out.println(u.getLastname());
}
So my question is:
What are the disadvantages of my implementation of the builder object? I can't really tell any (and I'm not saying there aren't any) so I would like to hear some feedback! Or is my code also a valid implementation of the builder object?
The difference in the implementations are that if you want to create multiple equal (or similar) but not same objects, you'll have to create a new Builder whereas with the other implementation you can do this:
Builder b = new User.Builder();
User john = b.firstName("John").lastName("Smith").build();
User jack = b.firstName("Jack").build();
I create this code just for my own understanding. I have a person class and a List to store all my Person objects. I added the same object twice to illustrate my question. How do I find the index of those objects?
How do I find the indexes of the two Andy Bernards?
public class Person {
private String firstName;
private String lastName;
public Person(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;
}
#Override public String toString()
{
return String.format(this.firstName + " " + this.lastName);
}
}
List<Person> deletePeople = new ArrayList<Person>();
Person createPerson = new Person("Andy","Bernard");
Person createTwo = new Person("Micheal","Scott");
deletePeople.add(createPerson);
deletePeople.add(createTwo);
deletePeople.add(createPerson);
/* for (Person display : deletePeople) {
if(display.getFirstName().equals("Andy")) {
System.out.println(deletePeople.indexOf(display));
}
} */
}
Firstly, add .equals() and .hashCode() methods to class Person so you can identify a Person object as being the same.
Second, use indexOf() and lastIndexOf() methods in class List to find the first and last Andy Bernard objects.
If what you really want is a list of indexes into the list where objects match your criteria, and there can be more than one, then you will need to iterate the list yourself, and save the indexes to some sort of list.
If what you want is simply to delete the matching items, then you can use java.util.Iterator (see http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html) to iterate over the collection, and invoke the Iterator's remove() method on each matching object as you encounter it.
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.