Java setters and getters - java

I have been struggling with setters and getters in java for quite a long time now.
For instance, if I want to write a class with some information as name, sex, age etc with appropriate set and get methods. Then in a another class I want to test my set and getters with this as a example:
personInfo = myInfo() = new Personinfo("Anna", "female", "17");
How do I do that?
I know that I can have a printout like:
public void printout() {
System.out.printf("Your name is: " + getName() +
" and you are a " + getSex());
}

This is a simple example to show you how to do it:
public class Person {
private String name;
private String gender;
private int age;
Person(String name, String gender, int age){
this.name = name;
this.gender = gender;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setGender(String gender){
this.gender = gender;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return this.name;
}
public String getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
public static void main(String[] args)
{
Person me = new Person("MyName","male",20);
System.out.println("My name is:" + me.getName());
me.setName("OtherName");
System.out.println("My name is:" + me.getName());
}
}
This will print out:
My name is:MyName
My name is:OtherName

Let eclipse handler it for you
Click on your variable
Source > Generate Setter / Getter

You need to create an object of one class in the other class. You can then call the .get() and .set() methods on them. I will post an example in 2 minutes
First class (i'll call it Person) will have methods to return its fields
private String name = "";
private String age = 0;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
The second class will call those methods after it creates an object of the first class
bob = new Person("Bob", 21);
System.out.println("Your name is: " + bob.getName() +
" and you are " + bob.getAge());

The point of getters and setters is to let you limit/expand the scope or functionality of your property, independent of each other.
You may want your 'name' property to be readonly outside of your PersonInfo class. In this case, you have a getter, but no setter. You can pass in the value for the readonly properties through the constructor, and retrieve that value through a getter:
public class PersonInfo
{
//Your constructor - this can take the initial values for your properties
public PersonInfo(String Name)
{
this.name = Name;
}
//Your base property that the getters and setters use to
private String name;
//The getter - it's just a regular method that returns the private property
public String getName()
{
return name;
}
}
We can use getName() to get the value of 'name' outside of this class instance, but since the name property is private, we can't access and set it from the outside. And because there is no setter, there's no way we can change this value either, making it readonly.
As another example, we may want to do some validation logic before modifying internal values. This can be done in the setter, and is another way getters and setters can come in handy:
public class PersonInfo
{
public PersonInfo(String Name)
{
this.setName(Name);
}
//Your setter
public void setName(String newValue)
{
if (newValue.length() > 10)
{
this.name = newValue;
}
}
Now we can only set the value of 'name' if the length of the value we want to set is greater than 10. This is just a very basic example, you'd probably want error handling in there in case someone goes jamming invalid values in your method and complains when it doesn't work.
You can follow the same process for all the values you want, and add them to the constructor so you can set them initially. As for actually using this pattern, you can do something like the following to see it in action:
public static void main(String[] args)
{
PersonInfo myInfo = new PersonInfo("Slippery Sid",97,"male-ish");
var name = myInfo.getName();
System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
myInfo.setName("Andy Schmuck");
System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
}

You create an object by instantiating the constructor as follows
Personinfo pi = new Personinfo("Anna", "female", "17");
You can then call methods upon that object as follows
pi.setName("Alan");
or
pi.getName();

here's how you do it:
public class PersonInfo {
private String name;
private String sex;
private int age;
/** GETTERS **/
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
/** SETTERS **/
public void setName(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public void setAge(int age){
this.age = age;
}
}
class Test{
public static void main(String[] args){
PersonInfo pinfo = new PersonInfo();
pinfo.setName("Johny");
pinfo.setSex("male");
pinfo.setAge(23);
//now print it
System.out.println("Name: " + pinfo.getName());
System.out.println("Sex: " + pinfo.getSex());
System.out.println("Age: " + pinfo.getAge());
}
}
Or you can add this as well:
#Override
public String toString(){
return "Name: " + this.name + "\n" +
"Sex: " + this.sex + "\n" +
"Age: " + this.age;
}
and then just to a .toString
EDIT:
Add this constructor in the class to initialize the object as well:
public PersonInfo(String name, String sex, int age){
this.name = name;
this.sex = sex;
this.age = age;
}

In personInfo:
public Person(String n, int a, String s){
this.name=n;
this.age=a;
this.sex=s;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getSex(){
return this.sex;
}
public void setName(String n){
this.name = n;
}
public void setAge(int a){
this.age = a;
}
public void setSex(String s){
this.sex = s;
}
Then fix the print statement:
System.out.println("Your name is: " + myInfo.getName() + " and you are a " + myInfo.getSex());

Related

define constructors in java

I am working on a java code to create a class Students and I should define two constructors and one has to be with parameters and one without parameters I have already done the one with parameters but I am having a problem understanding how to do the one without parameters This is what I have to do:
setStudent()that takes three parameters: a string name, an integer grade, and a double cgpa value.
It stores these parameters into the three member variables of the class.
getNamethat returns the value stored in the member variable name.
getGradethat returns the value stored in the member variable grade.
getCGPAthat returns the value stored in the member variable cgpa.
printStudent that displays the values of the three member variables.
I have done most but I do not know what to do with the last thing printStudent.
My class :
public class Students{
private String Name;
private int Grade;
private double CGPA;
public Students(String Name, int Grade, double CGPA){
this.Name = Name;
this.Grade = Grade;
this.CGPA = CGPA;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public int getGrade(){
return Grade;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public double getCGPA(){
return CGPA;
}
public void setCGPA(double CGPA){
this.CGPA = CGPA;
}
}
and that is my main :
public class LAB4EX1{
public static void main(String [] args){
Students student1 = new Students("Nasser", 90, 3.4);
Students student2 = new Students("Adnan", 92, 3.72);
Students student3 = new Students("Mohammed", 91, 3.5);
}
}
I need to make it print the output for me.
Any help would be really appreciated.
You have do declare a constructor without any parameters and override toString method:
public class Students{
private String Name;
private int Grade;
private double CGPA;
public Students(String Name, int Grade, double CGPA){
this.Name = Name;
this.Grade = Grade;
this.CGPA = CGPA;
}
public Students(){ // empty constructor
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public int getGrade(){
return Grade;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public double getCGPA(){
return CGPA;
}
public void setCGPA(double CGPA){
this.CGPA = CGPA;
}
#Override
public String toString() {
return "Students{" +
"Name='" + Name + '\'' +
", Grade=" + Grade +
", CGPA=" + CGPA +
'}';
} // toString() for printing your three fields
}

Check that the variable user have been Inputted is either String or not in Java : setter & getter?

I was practicing setter & getter in Java. I thought what if my code will through an error if user have set Employee name incorrect i.e. "123" or "#qre23" which can't be someone's name in real .Here is my code, suggest me what to upgrade ?
class MyEmployee {
private int id;
private String name;
public void setName(String name){
this.name = name;
}
public void getName(){
System.out.println("\n Your Employee Name is : " + this.name);
}
}
public class Main {
public static void main(String[] args) {
MyEmployee myEmployee = new MyEmployee();
myEmployee.setName("209");
myEmployee.getName();
}
}
Match the string with the Regex using matches()
public void setName(String name){
if(name.matches("^[a-zA-Z ]*$"))
this.name = name;
else
//throw error
}
You can do it in many different ways depending on what regex you want but this is one way to do it. Also make sure your getter returns a name. Right now, your getter doesn't return the name.
class MyEmployee {
private int id;
private String name;
public void setName(String name){
String regx = "^[\\p{L} .'-]+$";
boolean match = Pattern.matches(regx, name);
if(match){
this.name = name;
}
}
public String getName(){
System.out.println("\n Your Employee Name is : " + this.name);
return this.name;
}
}

Class with an ArrayList inside

I'm new to programming and i'd like some help.
I want to make a class that can add name,age and multiple phone numbers ( in some cases it will be 1, in others 4, etc...) and then show all the info.
I don't want to make it by creating another class for the ArrayList,
I'd like to do it all inside this class, I guess it's something simple to do but I can't figure this out and I'm not finding the solution I want.
what can I do about it? thx in advance, first time posting If I did something wrong please tell me.
import java.util.ArrayList;
public class Athlete
{
private String name;
private int age;
private ArrayList<String> phones = new ArrayList();
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public ArrayList<String> getPhones()
{
return phones;
}
public void setPhones(ArrayList<String> phones)
{
this.phones = phones;
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phones + '}';
}
}
You could make an inner class for PhoneList and use that type instead of directly working with the ArrayList.
public class Athlete
{
private String name;
private int age;
private PhoneList phoneList;
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
phoneList = new PhoneList();
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
// Maybe just return the toString (or a read only list)
public PhoneList getPhones()
{
return phoneList;
}
publicvoid addPhone(String phone)
{
phoneList.add(phone);
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phoneList + '}';
}
private class PhoneList
{
private ArrayList<String> list = new ArrayList<String>();
private void add(String phone)
{
list.add(phone);
}
#Override
public String toString()
{
StringBuffer b = new StringBuffer(32);
for (String ph : list)
{
b.append(ph + "\n"); // Or something
}
return b.toString();
}
}
}

Removing Duplicate Objects that contain different variables

I have two objects that have the same name but contain different ages(values), I tried adding these objects to a map to remove duplicates but it won't remove. This is the model code I am testing:
two ab = new two("john", "20");
two ac = new two("chan", "30");
two ad = new two("john", "34");
ArrayList<two> ae = new ArrayList<>();
public void adding(){
ae.add(ab);
ae.add(ac);
ae.add(ad);
System.out.println(ae);
}
public void removeDuplicate(){
Set<two> lhs = new HashSet<>();
lhs.addAll(ae);
ae.clear();
ae.addAll(lhs);
System.out.println(ae);
}
public static void main(String args[]){
one five = new one();
five.adding();
five.removeDuplicate();
}
This is the class that is used for object type:
package teeestserrr;
public class two {
private String name;
private String age;
public two(String name, String age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String toString(){
return name + " " + age;
}
}
Results are :
[john, chan, john]
[chan, john, john]
I also tried to make the toString return only name but the map used to remove duplicates doesn't seem to work even in that case. I don't understand and I cannot identify the underlying problem. Any help is appreciated.
You have to override equals and hashcode method in two.
Equals should give result according to only name field and also hashcode should be formed using only name field, that will help you to achieve your aim.
package teeestserrr;
public class two {
private String name;
private String age;
public two(String name, String age){
this.age = age;
this.name = name;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public String toString(){
return name + " " + age;
}
#Override
public boolean equals(Object obj){
if(obj==null)
return false;
if(name==null){
return false;
}
if(!(obj instanceof two)){
return false;
}
two another = (two)obj;
return this.name.equals(another.name);
}
public int hashCode(){
return name==null?0:name.hashCode();
}
}

constructor error

I was told that when creating a new object, it needs to have the same parameters as its constructor. Ive tried, but i still get these error. cannot find symbol s1.getCourse s1.getName s1.getAge. and also an invalid constructor error. heres my code
public class Person{
private String name;
private int age;
public Person(String name, int age){
this.name=name;
this.age=age;
}
public String getDetails(){
return "Name: " + name + "Age: " + age;
}
public void setName(String name){
this.name=name;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public class Student extends Person{
private String course;
public Student(String name, int age,String course){
super(name,age);
this.course = course;
}
public String getDetails(){
return super.getDetails()+"Course: "+ course;
}
public void setCourse(String course){
this.course=course;
}
public String getCourse(){
return course;
}
public String getName(){
return name;
}
}
public String getAge(){
return age;
}
}
TestPerson
student++;
String name=array[0];
int age=Integer.parseInt(array[1]);
String course=array[3];
Student s1= new Student(name,age,course);
System.out.println("name "+s1.getName());
System.out.println("age "+ s1.getAge());
System.out.println("course: " + s1.getCourse());
}
}
For more Detail can u provide Person class.
You have not provided the name and age attribute in student class.
if all this is present in super class then also When u call the s1.getName() method it will call from student class. because it present in sub class i.e student

Categories

Resources