Getter and Setter methods - java

I'm doing a Java assignment in Greenfoot and I'm stuck on a question about getter and setter methods which I cannot find an answer to.
I'm asked to write a getter and setter method for three attributes (name, colour, age) and then use these methods to:
(a) ensure that age cannot be less than 0 and age cannot be greater than 100
(b) ensure the only valid colours are Black, White, Brown and Grey
Any ideas or suggestions to how I would solve this problem?
Thanks in advance

I hope that help you, that will give you at least a visibility and you can modify it as you want :
public class MyClass {
private String name;
private int age;
private String color;
private final List<String> colors = Arrays.asList("Black", "White", "Brown ", "Grey");
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
if (colors.contains(color)) {
this.color = color;
} else {
// if not valid do what you want
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age <= 100) {
this.age = age;
} else {
// if not valid do what you want
}
}
}

I see that there is already a very nice code answer to your question, so i will focus on explaning getter and setter methods:
getter methods are used to get an atribute (also known as a field.) An atribute is usualy found in the top a program, for instance: private int i; i is an atribute. atributes can be accesed by all methods in the same class. so when writing a getter method you simply have to write:
public returntype getSomeAtribute(){
return someAtribute;
}
setter methods are used to set the value of an atribute, different types of atributes can have different values, boolean has true or false, int has integers, String has text. to set the value of a you simply overwrite the current value by writing:
public void setSomeAtribute(){
someAtribute = something;
}

Related

My getMethod does not return the value in the setMethod: Java

public class OOP_10_Encapsulation {
private String firstName;
private String favFood;
private int age;
private float weight;
//create a set method for firstName
public void setFirstName(String firstName){
this.firstName = firstName;
}
//create a get method for firstName
public String getFirstName(String firstName){
this.firstName = firstName;
return firstName;
}
//create a set method for favFood
public void setFavFood(String favFood){
this.favFood = favFood;
}
//create get method for favFood
public String getFavFood(String favFood){
this.favFood = favFood;
return favFood;
}
//create a set method for age
public void setAge(int age){
this.age = age;
}
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
//create a set method for weight
public void setWeight(float weight){
this.weight = weight;
}
//create a get method for weight
public float getWeight(float weight){
this.weight = weight;
return weight;
}
}
public class OOP_11_TestEncapsulation {
public static void main(String[] args) {
OOP_10_Encapsulation learner1 = new OOP_10_Encapsulation(); //create object of OOP_10_Encapsulation
learner1.setFirstName("Evander O A");
learner1.setAge(31);
learner1.setWeight(98.6F);
learner1.setFavFood("waakye");
System.out.println("Hi, my name is " + learner1.getFirstName());
}
}
I have this challenge that I am not able to get my head around. When I run the code in the main method, the get method does not return the name "Evander O A" as set in the set method. Actually, none of my get methods are getting anything I need them to get.
Let's look at one of your get methods:
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
The purpose of a get method, also called "getter" is to get something from inside an object, usually it's some of the object's attribute that you wanna get.
If you just want to get an attribute, there is no need to pass a parameter to the get method:
public int getAge(int age) // age parameter is useless
Not only that it is useless here, but you are also doing something wrong, in the get method you are first changing attribute's value. You are effectively doing a set inside a getter method:
this.age = age; // wrong
Given your code for getAge method, let's see how it will execute when you call something like:
System.out.println("Hi, my name is " + learner1.getAge())
The function getAge will be called with no parameter, although it is expecting one. So most probably you won't be able to compile this piece of code.
I got the following error when trying to compile something similar:
https://imgur.com/a/4AVwMke
So if you create a function with 1, 2, 3 or whatever number of parameters then you must call it using the same number of arguments to the function call. Otherwise most probably that code won't run.
Now let's assume I call it with some value as argument, probably you did too.
System.out.println("Hi, my name is " + learner1.getAge(0))
This is going to happen:
//create a get method for age
public int getAge(int age // which is 0){
this.age = age; // you set the age to 0, losing the old value
return age; // you return 0, because you no longer have the old value
}
How should you do it? Simple:
//create a get method for age
public int getAge(){
return age;
}
Now apply this fix to all of your getters (the get methods) and you are good to go. Let me know if something is not clear.

it's print null in console when I run a program in Java

`
package Stuff;
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
studentName = name;
studentAge = age;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
`
I Don't Know where is the wrong in code the console print me (null) when i request student1.printName() and 0 When i request Student.printAge()
Your variable assignments in the constructor are the wrong way around.
You are assigning the variables in the constructor in wrong way. The correct way will be:
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
If you auto-generate the constructors then it will look like this, which is more common convention:
public Student(String name,int age){
this.name = name;
this.age = age;
}
You messed up the initialization part studentname = name and studentage = age the right way of initialization is given down
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
The constructor should be like
public Student(String studentName,int studentAge){
this.name = studentName;
this.age = studentAge;
}
I highly recommend that you have a look at this article on associativity in Java.
Basically, when you assign a value to a variable using the = operator, the statement is carried out from right to left. Hence, the outcome of the expression on the Right Hand Side is assigned to the variable on the Left Hand Side.
Hence, int a = 5+5 means that the outcome of 5+5 is stored in variable a. This is also why studentName = name assigns the value of name (which is the default value of the String type - null) to studentName.
It is also important to note that null is a keyword in Java, and if you print null like this:
System.out.println(null)
A Syntax Error will be thrown (which is for a different reason).
EDIT - At the time of typing this out, there was only one answer, and not explanatory in any way. Now, I see there are more. Although the other answers may tell you what to do, I figured that this answer would tell you how to think in Java, so that you make no such mistakes again.

Convert Parent Class to child in java

Consider this scenario,
I have two classes Student and HonorsStudent respectively.
class Student{
String name;
int roll;
Student(String name, int roll){
this.name = name;
this.roll = roll;
}
}
class HonorStudent extends Student{
int honorid;
HonorStudent(String name, int roll,int honorid){
this.name = name;
this.roll = roll;
this.honorid = honorid;
}
HonorStudent(String name, int roll){
this.name = name;
this.roll = roll;
}
}
Now, there might be scenarios in which I might want to convert a Student into an HonorStudent. Since downcasting is not allowed in this situation, I can't do this:
Student s1 = new Student("abc",123);
HonorStudent s = (HonorStudent)s1;
So the other way of doing this would be to define a method in HonorStudent which inputs a Student Object and returns a HonorStudent:
public static HonorStudent convertToHonor(Student s){
return new HonorStudent(s.name,s.roll);
}
This is convenient if there are only two attributes(name, roll), but what if I have a lot of attributes say 50 ? In that case I would have to input each and every attribute into HonorStudent?
I strongly feel there might be an easier way to do this?
You are asking if there is a more convenient way to do this. If we consider just copying parameters from one object to another then there is no another way to do this. There might be ways to work around the problem by having objects for groups of member fields or by automating it by code that can copy member fields with same name from object to another.
Small fix
But first, let's improve design a bit. Fields should not be duplicated like this between classes in a class hierarchy. So let's eliminate that duplication:
public class Student {
private String name;
private int roll;
public Student(String name, int roll) {
this.name = name;
this.roll = roll;
}
public String getName() {
return name;
}
public int getRoll() {
return roll;
}
}
public class HonorStudent extends Student {
private int honorId;
public HonorStudent(String name, int roll, int honorId) {
super(name, roll);
this.honorId = honorId;
}
public int getHonorId() {
return honorId;
}
}
Copy constructor
If there is really a need to copy objects then copy constructor can be useful. Creating a copy constructor will allow you to skip passing each member field only by one.
public Student(Student other) {
this.name = other.name;
this.roll = other.roll;
}
Then creating Student part of the HonorStudent becomes simpler
public HonorStudent(Student student, int honorId) {
super(student);
this.honorId = honorId;
}
Design
Now it is not common that objects change their type. So this is not a common thing to do. This is usually solved by different kind of design of classes. For example, honorId could be part of Student class because, I guess, student can gain this attribute or loose it. Behaviour related to honor can be in some other class that is attached to student class.
Reading about behavioural design patterns can be useful. Depending which pattern to choose will depend on the use case and the problem that you are trying to solve.

Using Eclipse, trying to get a program to work

I am currently learning Java with eclipse for my computer science course, and I need some assistance trying to figure out how to fix the error that is currently showing.
package sec4Les2;
public class RoseDS4L2Person {
//creating the variables
public String name = "Uma Thurman";
public int Age = 0;
//constructor
public RoseDS4L2Person()
{
}
public String getname()
{
//will return first name
return name;
}
public int getAge()
{
//will return age
return Age;
}
public void setAge(int Age)
{
//will set age to int
this.Age = Age;
}
}
And here is the running code:
package sec4Les2;
public class RoseDS4L2ManagingPeople {
public static void main(String[] args) {
//runs information in first class file
RoseDS4L2Person p1 = new RoseDS4L2Person("Arial", 37);
RoseDS4L2Person p2 = new RoseDS4L2Person ("Joseph", 15);
if(p1.getAge()==p2.getAge())
{
System.out.println(p1.getname()+" is the same age as "+p2.getname());
}
else
{
System.out.println(p1.getname()+" is NOT the same age as "+p2.getname());
}
}
}
It says there are no errors on the first one, but the second one has errors on the p1/p2 lines. How can I fix this error? thank you!
You should have a constructor for RoseDS4L2Person accepting a string and a number, like so:
public RoseDS4L2Person(String name, int age)
{
this.name = name;
this.Age = age;
}
This will allow you to create an instance of the class passing a name and an age as parameters.
You need to add this code to your class. Basically, a constructor was missing in your class. Also note that by convention, member variables start in lowercase. So your Age should really be age.
Another thing is, you have kept name as constant. Probably you want to remove "Uma Thurman". If you want to keep that as default name for all objects where name is not specified at initialization time, you would want to add that in the constructor. *
public class RoseDS4L2Person
{
// other lines ....
RoseDS4L2Person(String name, int age) {
this.Age = age;
this.name = name;
}
}
*
Something like this:
public class RoseDS4L2Person
{
private static final String UMA_THURMAN = "Uma Thurman";
// other lines ....
RoseDS4L2Person( int age) {
this.Age = age;
this.name = UMA_THURMAN;
}
}
The error is popping up because you have created objects with a non-existing constructor.Making objects with the default constructor or creating a constructor
which can accept the arguments you pass should do the trick.
Happy Coding

How to create get and set methods for parameters in a class? [duplicate]

This question already has answers here:
How do getters and setters work?
(6 answers)
Closed 7 years ago.
I have a class I created.
public class mailCustomer {
public static void main(String[] args) {
String Name;
int Id;
String Address;
Boolean IsPack;
}
}
I need to creat get and set methods for my parametrs, Name, Id,Address, IsPack.
how do I do that, and where do I write them? after the "main" method? in the "main" method?
Firstly, you need to declare the variables at the class level so that they can be used from anywhere within the class. Then after that you simply create a set and get method for each variable, like so
public class MailCustomer {
String name;
int id;
String address;
boolean isPack;
public static void main(String[] args) {
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setAddress(String address) {
this.address = address;
}
public void setIsPack(boolean isPack) {
this.isPack = ispack;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getAddress() {
return address;
}
public boolean getIsPack() {
return isPack;
}
}
It also appears that you have your naming conventions a little mixed up. In java, class names are capitalized, whereas variable and method names are camelCased
First, delete the main method from there. You are creating a class called mailCustomer that will create you object type of mailCustomer.
For this, you need three things: attributes (you have them there), a constructor and get/set methods. I will show you with a example, and you can guide from there. My class will be 'Rabbit' and it will have:
Attributes
-String eyes: Eye colour.
-String race: Where is it from.
Constructor
It will have one constructor, that will use both parameters.
Methods
It will have two getters and two setters, both for each attribute.
Here's my code for this class:
public class Rabbit{
//Attributes
private String eyes;
private String race;
//Constructor
public Rabbit(String colour, String where){
this.eyes = colour;
this.race = where;
}
//Methods get/set
public String getEyes(){
return this.eyes;
}
public String getRace(){
return this.race;
}
public void setEyes(String colour){
this.eyes = colour;
}
public void setRace(String where){
this.race = where;
}
}
As you can see, you will use get methods to return an specific attribute from the class; and set methods will be used if you want to change one of the attributes from a created object (in my case, from a created 'Rabbit').
Later, if you want to make use of this class, you will create your Main class, into the same package where 'Rabbit' class is created.
package rabbit;
public static void main(String[] args){
Rabbit George = new Rabbit("brown","spanish");
}
Now try to do this with your class. I hope it helped you!
public static void main(String[] args) {
String Name;
int Id;
String Address;
Boolean IsPack;
}
You can't create getters and setters for these, since they are not created in your class, but locally in your main method. What you want is:
public class MyClass{
String Name;
int Id;
String Address;
Boolean IsPack;
// getter for Name
public String getName(){
return this.Name;
}
// setter for Name
public void setName(String name){
this.Name = name;
}
public static void main(String[] args) {
}
}
For these you'll be able to create getters and setters.
It's (most likely) best to declare them private, though.
Also: following naming conventions could help other people easier read your code. Name (with capital N) is more suited as name of a class, while name (lowercase n) is the name of a variable.
As already said it seems that you are not familiar with Object Oriented Programming. It does not care. I just want to say that you can save a lot of time and improve your classes readability using lombok to automatically generate your getters and setters using annotations. You can find an example here : LOMBOK

Categories

Resources