Getters, Setters and ToString

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

35 Replies - 1782 Views - Last Post: 28 November 2011 - 07:41 PM Rate Topic: -----

#1 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Getters, Setters and ToString

Posted 28 November 2011 - 02:18 PM

Hi guys i have a bit of a problem with my code what i have to do is create a class called persona and in that class i have name and number and what m program is supposed to do is create,alter and list new names and give it a number and with a counter add more but im having a bit off a problem because i dont get how to use the getters, setters and toStrings can anyone one help i already tried many things but the closest option i got was implementing a single static name and number and i have to add three diferent ones


package projinter1;

import java.util.Scanner; 
class Person{
  String name;
    String number;
    
private String Name,Numero;
public String getName(){return name;}
public void setName(String a){name=a;}
public String getNumber(){return number;}
public void setNumber(String pn){number=pn;}


Person(){  
Name=Number=null;
}


Person(String a,String pn){
name=a;
number=pn;
}


void print()
{
System.out.println(" Number: " + number + "  Name: " + name);
}
  
public static void main (String args[])
{
    Scanner in = new Scanner(System.in);
      int option=4; 
     System.out.println("|--------------Menu Principal-----------|");
     System.out.println("|                                       |");
     System.out.println("|             1-Create                  |");
     System.out.println("|               2-alter                 |");
     System.out.println("|                3-List                 |");
     System.out.println("|                   4-Exit              |");
     System.out.println("|                                       |");
     System.out.println("|---------------------------------------|");
    do {
   option = in.nextInt();
         
   switch(option){
             case 1:
                 break;
              case 2:
               //*  alter();
                 break;
              case 3:     
                Person event;
                    event=new Person("Antonio","Viegas");
                        event.print();
                 break; 
              case 4:
                 System.exit(0);
                 break;
         }
    }while (option!=4);
    }   
                  


This post has been edited by reynaud0000: 28 November 2011 - 02:22 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Getters, Setters and ToString

#2 SwiftStriker00  Icon User is offline

  • No idea why my code works
  • member icon

Reputation: 433
  • View blog
  • Posts: 1,596
  • Joined: 25-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 02:44 PM

First I cleaned up your code so it was easier to read. and I changed the variable number into an int (integer) so it was actually a number. Then I added a counter, so you can see how you can keep increasing the value as you create new people

package projinter1;

import java.util.Scanner; 

public class Person{
    
	private String name;
	private int number;
	
	Person()
	{  
		name= "";
		number=0;
	}
	
	Person(String a, int pn){
		name=a;
		number=pn;
	}
	
	public String getName()
	{
		return name;
	}
	
	public void setName(String a)
	{
		name=a;
	}
	
	public int getNumber()
	{
		return number;
	}
	public void setNumber(int pn){
		number=pn;
	}
	
	void print()
	{
		System.out.println(" Number: " + number + "  Name: " + name);
	}
  
	public static void main (String args[])
	{
		Scanner in = new Scanner(System.in);
		int option=4; 
		System.out.println("|--------------Menu Principal-----------|");
		System.out.println("|                                       |");
		System.out.println("|             1-Create                  |");
		System.out.println("|               2-alter                 |");
		System.out.println("|                3-List                 |");
		System.out.println("|                   4-Exit              |");
		System.out.println("|                                       |");
		System.out.println("|---------------------------------------|");
		
		int counter = 0;
		
		do {
			option = in.nextInt();
         
			switch(option){
				case 1:
					break;
				case 2:
					//*  alter();
					break;
				case 3:     
					Person event;
					event=new Person("Antonio", counter);
					counter++;
					event.print();
					break; 
				case 4:
					System.exit(0);
					break;
			}
		} while (option!=4);
    }
}




Was This Post Helpful? 0
  • +
  • -

#3 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 02:50 PM

View PostSwiftStriker00, on 28 November 2011 - 02:44 PM, said:

First I cleaned up your code so it was easier to read. and I changed the variable number into an int (integer) so it was actually a number. Then I added a counter, so you can see how you can keep increasing the value as you create new people

package projinter1;

import java.util.Scanner; 

public class Person{
    
	private String name;
	private int number;
	
	Person()
	{  
		name= "";
		number=0;
	}
	
	Person(String a, int pn){
		name=a;
		number=pn;
	}
	
	public String getName()
	{
		return name;
	}
	
	public void setName(String a)
	{
		name=a;
	}
	
	public int getNumber()
	{
		return number;
	}
	public void setNumber(int pn){
		number=pn;
	}
	
	void print()
	{
		System.out.println(" Number: " + number + "  Name: " + name);
	}
  
	public static void main (String args[])
	{
		Scanner in = new Scanner(System.in);
		int option=4; 
		System.out.println("|--------------Menu Principal-----------|");
		System.out.println("|                                       |");
		System.out.println("|             1-Create                  |");
		System.out.println("|               2-alter                 |");
		System.out.println("|                3-List                 |");
		System.out.println("|                   4-Exit              |");
		System.out.println("|                                       |");
		System.out.println("|---------------------------------------|");
		
		int counter = 0;
		
		do {
			option = in.nextInt();
         
			switch(option){
				case 1:
					break;
				case 2:
					//*  alter();
					break;
				case 3:     
					Person event;
					event=new Person("Antonio", counter);
					counter++;
					event.print();
					break; 
				case 4:
					System.exit(0);
					break;
			}
		} while (option!=4);
    }
}





Thank you very much for organizing my code better sorry it was so desorganized but my main problem is still the getters setter and toString for a simple reason i dont know how to invoke the variables with the get and then how to use the set so i can alter and create new ones

This post has been edited by smohd: 28 November 2011 - 04:56 PM
Reason for edit:: removed other statements from quote block

Was This Post Helpful? 0
  • +
  • -

#4 SwiftStriker00  Icon User is offline

  • No idea why my code works
  • member icon

Reputation: 433
  • View blog
  • Posts: 1,596
  • Joined: 25-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 02:57 PM

Once you create a person:

Person p = new Person( "bob" , 0 );

your client will not know what those private variables( name, number) that you created. So we use getters and setters to access and change those values.

Lets say the client wants p's name. We need the name getter/accessor
String Pname = p.getName();

Now if we want to change p's name, we need a setter/mutator
p.setName( "Jim" );

This will change the values of those private variables.

ToString creates a string representation of the object. Usually for debugging purposes
if we wanted P's information we could go:
System.out.print( "P's name is: " + p.getName() );
System.out.println( "P's number is: " + p.getNumber );


however it would be easier if we defined a toString method to do it all in one method:
System.out.println( p.toString() );


This post has been edited by SwiftStriker00: 28 November 2011 - 02:58 PM

Was This Post Helpful? 0
  • +
  • -

#5 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 03:06 PM

View PostSwiftStriker00, on 28 November 2011 - 02:57 PM, said:

Once you create a person:

Person p = new Person( "bob" , 0 );

your client will not know what those private variables( name, number) that you created. So we use getters and setters to access and change those values.

Lets say the client wants p's name. We need the name getter/accessor
String Pname = p.getName();

Now if we want to change p's name, we need a setter/mutator
p.setName( "Jim" );

This will change the values of those private variables.

ToString creates a string representation of the object. Usually for debugging purposes
if we wanted P's information we could go:
System.out.print( "P's name is: " + p.getName() );
System.out.println( "P's number is: " + p.getNumber );


however it would be easier if we defined a toString method to do it all in one method:
System.out.println( p.toString() );


but if i want to write the name i still have to use a scanner, for example you put the name jim in there but i cant change it do i put it like this

int as; 
Scanner s = new Scanner(System.in);
 as=s.p.setName();




or like this


p.setName(System.in);

This post has been edited by macosxnerd101: 28 November 2011 - 03:16 PM
Reason for edit:: Fixed quote tag

Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10573
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 03:14 PM

The big deal with getter and setter methods goes towards encapsulation and providing only necessary access. Getter and setter methods can be overridden in child classes to further control read/write access.

Regarding the toString() method, it's purpose is to return a String representation of an Object. It is defined initially in the Object class, so all classes inherit it. The Object toString() method just returns the memory location and class name. The reason you would want to override the toString() method is to provide a more human friendly description of your Object.

Quote

System.out.println( p.toString() );


The toString() method is invoked automatically if you pass p.

Dogstopper has a good tutorial on the toString() method as well.

Hope this helps some! :)

Edit:

In the case of using something to get user input, what you do is read in the input normally. Then you invoke the Object's setter method to update the value.
String name = scan.nextLine();
p.setName(name);


Was This Post Helpful? 0
  • +
  • -

#7 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 03:23 PM

View Postmacosxnerd101, on 28 November 2011 - 03:14 PM, said:

The big deal with getter and setter methods goes towards encapsulation and providing only necessary access. Getter and setter methods can be overridden in child classes to further control read/write access.

Regarding the toString() method, it's purpose is to return a String representation of an Object. It is defined initially in the Object class, so all classes inherit it. The Object toString() method just returns the memory location and class name. The reason you would want to override the toString() method is to provide a more human friendly description of your Object.

Quote

System.out.println( p.toString() );


The toString() method is invoked automatically if you pass p.

Dogstopper has a good tutorial on the toString() method as well.

Hope this helps some! :)

Edit:

In the case of using something to get user input, what you do is read in the input normally. Then you invoke the Object's setter method to update the value.
String name = scan.nextLine();
p.setName(name);



First of all thanks for clarifing what is the toString really thanx XD and second i wanna input the results with a scanner instead of having them input by the static metod do you know how to do it?

This post has been edited by macosxnerd101: 28 November 2011 - 03:38 PM
Reason for edit:: Please do not post your question inside the quote tags

Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10573
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 03:40 PM

My last code sample shows how to do it. No static methods are involved. The scan variable is a Scanner and p is your Person object.
Was This Post Helpful? 0
  • +
  • -

#9 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 04:08 PM

It isnt working like i want to i want to add at least 3 names but for that i have to do an array but i gives me an error and i dont know what to do and i cant change the name e dont know what im doing wrong in neither of them

package projinter1;

import java.util.Scanner; 

class Person{
    
	private String name;
	private int number;
	
	Person()
	{  
		name= "";
		number=1;
	}
	
	Person(String a, int pn){
		name=a;
		number=pn;
	}
	
	public String getName()
	{
		return name;
	}
	
	public void setName(String a)
	{
		name=a;
	}
	
	public int getNumber()
	{
		return number;
	}
	public void setNumber(int pn){
		number=pn;
	}
	
	void print()
	{
		System.out.println(" Number: " + number + "  Name: " + name);
	}
  
	public static void main (String args[])
	{
            Person p = new Person( "", 1 );
		Scanner in = new Scanner(System.in);
		int option=4; 
		System.out.println("|--------------Menu Principal-----------|");
		System.out.println("|                                       |");
		System.out.println("|             1-Create                  |");
		System.out.println("|               2-Alter                 |");
		System.out.println("|                3-List                 |");
		System.out.println("|                   4-Exit              |");
		System.out.println("|                                       |");
		System.out.println("|---------------------------------------|");
		
		int counter;
		
		do {
			option = in.nextInt();
         
			switch(option){
				case 1:
                                    
                                    System.out.println(" Insert Name: ");
                                    Scanner scan = new Scanner(System.in);
                                  String name = scan.nextLine();
                                    p.setName(name);
					break;
                                    
				case 2:
					String Pname = p.getName();
                                        Scanner scan1 = new Scanner(System.in);
                                        name = scan1.nextLine();
                                        p.getName();
                                        p.setName(name);
                                        
					break;
				case 3:    
                                 
					Person event;
                                        counter=p.getNumber();
					event=new Person( p.getName() , counter);
					counter++;
					event.print();
                                    
					break; 
                                   
				case 4:
					System.exit(0);
					break;
			}
		} while (option!=4);
    }
}




View Postmacosxnerd101, on 28 November 2011 - 03:40 PM, said:

My last code sample shows how to do it. No static methods are involved. The scan variable is a Scanner and p is your Person object.

This post has been edited by reynaud0000: 28 November 2011 - 04:17 PM

Was This Post Helpful? 0
  • +
  • -

#10 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 04:50 PM

can anyone tell me if i can use my variable name as an array
?
and can anyone tell me what im doing wrong in the part of my code where i try to alter the name?
Was This Post Helpful? 0
  • +
  • -

#11 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10573
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 05:13 PM

No, you cannot use name as a Person[]. What you want is a Person[] in your main() method and manage that.

Beyond that, what specific problems or errors are you encountering?
Was This Post Helpful? 0
  • +
  • -

#12 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 05:18 PM

View Postmacosxnerd101, on 28 November 2011 - 05:13 PM, said:

No, you cannot use name as a Person[]. What you want is a Person[] in your main() method and manage that.

Beyond that, what specific problems or errors are you encountering?

beyond that the problem im encountering is related to the altering part i dont know what im doing wrong there

but by the way i didnt quite understand what you meant whit the Person[] in the main i have this

Person p = new Person( "", 1 );

i cant make an array here can i?
Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10573
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 05:24 PM

Rather than managing a single Person, declare an array instead.
public static void main(String[] args){
    Person[] people = new Person[10]; //an array that can hold 10 Person objects
}



You will also find it helpful to manage an index variable to track which elements in the array are populated with Person objects.

You may also find my tutorial Moving Away From Parallel Arrays helpful, as it discusses OOP and using classes and objects in this manner.
Was This Post Helpful? 0
  • +
  • -

#14 reynaud0000  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 19-June 11

Re: Getters, Setters and ToString

Posted 28 November 2011 - 05:35 PM

View Postmacosxnerd101, on 28 November 2011 - 05:24 PM, said:

Rather than managing a single Person, declare an array instead.
public static void main(String[] args){
    Person[] people = new Person[10]; //an array that can hold 10 Person objects
}



You will also find it helpful to manage an index variable to track which elements in the array are populated with Person objects.

You may also find my tutorial Moving Away From Parallel Arrays helpful, as it discusses OOP and using classes and objects in this manner.


one question if i have the array that is not in the class can i still save the values in the class?

because even if you do i dont see how i tried saying this
people=p.setName(name);

but it gives me an error
Was This Post Helpful? 0
  • +
  • -

#15 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10573
  • View blog
  • Posts: 39,151
  • Joined: 27-December 08

Re: Getters, Setters and ToString

Posted 28 November 2011 - 05:39 PM

You can still use getter/setter methods on the objects. However, setName() is void and doesn't return anything. So you cannot assign p.setName(name); to a variable. Second, people is a Person[]. You can only assign a Person[] or null to people.

The way arrays work is by storing the elements according to numeric indices. So a Person[] stores Person objects. And as an example, people[0] would refer to the first element in the array. You would treat people[0] like a normal Person variable and invoke methods on that.

It sounds like you might want to brush up on your knowledge of arrays as well. I think this tutorial is a good one to check out.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3