Getters in Java for novice java users - java

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.

Related

Cannot resolve symbol in Java. I want to run the code of second class in the first class

I am learning Java from tutorials, and recently I faced with one problem. I need to create several classes, and I need to read all that classes through first class. Already I passed that tutorial where I understood everything and tried that thing. But now I want to create a real world app on Java, I did the exact thing which was showing in tutorial, but I am getting that error. Please, correct me where I have mistaken
Code of first class:
package com.company;
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println(em);
}// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
}
Second one:
package com.company;
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
}
}
Screenshotes:
Thanks
You can use System.out.println(this) in constructor. It means that you will print created instance to console. And also don't forget to override toString() method - because if you don't override it, you will get object's name with hashcode.
Hope this code will help you to reach the goal:
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println(this);
}
// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
#Override
public String toString() {
return "Email{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Another solution. Just override toString of Email class. And put printing of em to main method.
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
#Override
public String toString() {
return "Email{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Main class:
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
System.out.println(em);
}
}
The constructor of your Email Class does not have a variable called em.
You should put System.out.println(em) into the Main method of your EmailApp class.
The object reference "em" has no scope in first class i.e. class Email.
make these following two changes and compare your code. you will understand where you went wrong.
//-----------------------------------------------------change 1
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
and in second class:
//---------------------------------------------change 2
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
System.out.println(em.firstname);
System.out.println(em.lastname);
}
}
and make all member variables public for now. You will make it private when you understand "getters and setters" concept.

Check if object with same properties exist - Static factory method

Using static factory method, I want to create objects (e.g. persons), but throw an error/exception if a person with the same criteria is being created.
I have 2 classes Person.java / Program.java (<-Main)
My static method is as follow:
public class Person{
private String firstName;
private String lastName;
private Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public static Person fullName(String firstName, String lastName){
/*if(firstName.equals(this.firstName)){
System.out.println("Person already exists!");
}else{
return new Person(firstName,lastName);
}*/
return new Person(firstName, lastName);
}
}
Now obviously the commented-out part wouldn't work because Person isn't instanciated, but I'm kind of lost about how I could go on.
And yes, I'm overriding equals and hashcode!
To achieve it you should keep traces of all created instances in the Person class by using a static collection.
Note that it may cause memory retention if you don't use weak references for them and these are only referenced by the collection defined in Person.
Then about the check of an existing Person, as you overrided equals() and hashCode(), you could create a new Person from the parameters and check whether it was already created.
public class Person{
private String firstName;
private String lastName;
private static Set<Person> persons = new HashSet<>();
private Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
// equals and hashCode overrided relying on firstName and lastName fields
// ..
// Aditionnally to ease the creation of the exception message, override toString() too
#Override
public String toString(){
return "name=" + name +", lastName=" + lastName);
}
public static Person fullName(String firstName, String lastName){
Person p = new Person(firstName, lastName);
if (persons.contains(p)){
throw IllegalArgumentException("person " + p " already created";
}
persons.add(p);
return p;
}
}

Which of these ways is better in Java? [duplicate]

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;
}
}

Get and set to private variables in java

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.

Creating a class with different argument lengths

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;
}
}

Categories

Resources