Objected Oriented Programming- How to use the toString() method and format()? - java

I have just started doing object oriented programming as part of my course, but I am struggling with it, specifically the toString method in a Person Class. I need to write a toString() method to display the contents of instance variables.
I need to by sample print out:
Person[forName=joe, surname= smith, age= 25, height= 1.57, gender= male]
I also need to format it like this using the format method:
smith joe 25 1.57 male
davis sian 18 1.73 female
*** *** *** *** ***
I havent written a tester yet, but here is what I have written so far for the class and now I'm stuck, I'm not even sure if I am getting the toString statement wrong. I am using netBeans for this:
public class Person
{
private String surname;
private String forname;
private int age;
private double height;
private String gender;
public String toString()
{
return getClass().getName() + "[surname= " + surname + " forname= " + forname + " age= " + age + " height= " + height + " gender " + gender + "]";
}
}
What I need to do is make a class called Person that I can test. It needs to be able to hold the five variables above (surname etc) for different people. I need to be able to print out each of the instance variables with a toString() method and to use a format() method to produce a string with formatting infomation in order for the string printed out by the toString() method to be formatted like the second quotation.
Am I on the right track and regardless, how can I work through this?
EDIT: I have looked at the Person Class and have done what I can with it, does it seem decent enough? I am going to try and get a PersonTester together.
public class Person
{
private String surName;
private String forName;
private int age;
private double height;
private String gender;
#Override
public String toString()
{
return getClass().getName() + "[surName= " + surName + " forName= " + forName + " age= " + age + " height= " + height + " gender " + gender + "]";
}
public void format()
{
System.out.format("%10s%10s%10d%10f%10s", "surName", "forName", age, height, "gender");
}
public String getSurName()
{
return surName;
}
public String getForName()
{
return forName;
}
public int getAge()
{
return age;
}
public double getHeight()
{
return height;
}
public String getGender()
{
return gender;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public void setForName(String forName)
{
this.forName = surName;
}
public void setAge(int age)
{
this.age = age;
}
public void setHeight(double height)
{
this.height = height;
}
public void setGender(String height)
{
this.gender = gender;
}
}
EDIT 2: Started on a class Tester, but I am running into errors again about the setter's not having a ; and not being a statement.
Here's the tester so far:
public class PersonTester
{
public static void main(String[] args)
{
System.out.println("PersonClassTester");
System.out.println("*****************");
System.out.println("");
Person joeSmith = new Person();
String "smith" = joeSmith.setSurName();
String "joe" = joeSmith.setForName();
int 25 = joeSmith.setAge();
double 1.57 = joeSmith.setHeight();
String "male" = joeSmith.setGender();
joeSmith.toString();
joeSmith.format();
}
}

First of all you have to noticed that every object you create extends class Object. This Object class contains methods like toString, equals, hashCode...
your object have also this methods(inherited from Object). When you override (you should annotate this method with #Override) for eg. toString you will always use this toString method instead of inherited one. Its called polymorphism. Your toString method looks fine. In your main method you should use some kind of loop through all Persons and there format the output from toString method.
You have error in your code
public String toString(); {
remove the ; after ()
public class Main {
public static void main(String[] args) {
Person a = new Person("smith", "joe", 25, 1.57, "male");
Person b = new Person("davis", "sian", 18, 1.73, "female");
List<Person> persons = new ArrayList<Person>();
persons.add(a);
persons.add(b);
for(Person p : persons){
System.out.format("%s %s %s %d %.2f %s", p.getClass().getName(), p.getSurname(), p.getForname(), p.getAge(), p.getHeight(), p.getGender());
System.out.println();
}
}
}
If you call this
System.out.println(p.toString());
than you ll get your person via toString method.
I just edit your Person class and add constructor and geters + seters
public Person(String surname, String forname, int age, double height,
String gender) {
super();
this.surname = surname;
this.forname = forname;
this.age = age;
this.height = height;
this.gender = gender;
}
Here is geter and seter sample.
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}

As already mentioned your toString() is fine.
Please note that the toString() method and the format() method are IMO supposed to work independently as they do serve different purposes.
I suggest to put the format method not in the person class (or at least make it static method). This is because a single Person instance has not enough information for it to be printed in the table format. It at least needs to know the column widths. Otherwise you could end up with something like this:
smith joe 25 1.57 male
someVeryLongFirstName sian 18 1.73 female
*** *** *** *** ***
So the format method should take a list of persons that should be printed out and then first calculate the column widths. After this is done you then just pad the property value to the column width and print this out.

You are on the right track:
Inside of the Person class you need to add public methods for each private variable to set the data:
public void setAge(int age) {
this.age = age;
}
Then you can create a Person object in your main class and set his age:
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setAge(15);
}
}
As an alternative, you can use a constructor inside of your Person class to set your object's variables:
public Person(String surname, int age) {
this.surname = surname;
this.age = age;
}
And create the object in the main method like this:
Person p = new Person("Nillas", 25);
You can always run your toString() method in the main class after you've created the object and see the result:
System.out.println(p.toString());
Hope this helps, good luck!

Related

How to return variable that is exclusive to one subclass?

I have class Person which has multiple subclasses. All subclasses have the same variables (name, address, phone), but one has an extra variable, rank. I know how to display name, address, phone but I don't know how to display rank.
Define class:
public class Person {
public String name;
public String address;
public String phone;
public Person(String name, String address, String phone) {
this.name = name;
this.address = address;
this.phone = phone;
}
public String toString() {
return this.getClass().getName() + "\n" + name;
}
}
Define the subclass with rank:
public class Pupil extends Person {
public String rank;
public Student(String name, String address, String phone, String rank) {
super(name, social, phone);
}
}
Create pupil and display name, address, and phone.
public class Test {
public static void main(String[] args) {
Person person = new Person("John", "1 John Deer Rd", "1112223333");
Person pupil = new Pupil("Jane", "2 John Deer Rd", "1112223333", "junior");
System.out.println(pupil.name + "'s phone is " + pupil.phone + " and their address is " + pupil.address + "." + "\n");
}
}
How do I also display rank?
You have to cast the object from Person back to Pupil:
((Pupil)pupil).rank
And if you are not 100% sure that your object is actually a Pupil you should add a sanity-check:
if(pupil instanceof Pupil) {
System.out.println(…+((Pupil)pupil).rank+…);
}
You can use Pupil 's constructor instead of Person's constructor
public class Pupil extends Person {
public String rank;
public Pupil (String name, String address, String phone, String rank) {
super(name, social, phone);
}
}
Pupil pupil = new Pupil("Jane", "2 John Deer Rd", "1112223333", "junior");pupil = new Pupil("Jane", "2 John Deer Rd", "1112223333", "junior");
System.out.println(pupil.name + "'s phone is " + pupil.phone + " and their address is " + pupil.address + "." + "\n"+pupil .rank);
I suggest using getter and setter methods and use them and make your fields private.
You can read more about setter and getter methods
a quick example:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name =name;
//get name parameter and set it to this class'sname parameter }
Last but not least, I recommend that you read about this keyword
be happy.

If I create an array of the parental class, how do I access a method from the sub class through the array object?

I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();

Set , Get Method in Java

I am just starting to get into Object Oriented Programming in Java. I am curious about what the difference (if any) is between the 2 pieces of code below.
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
This is the 2nd piece of code;
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
I prefer the 2nd piece of code here because its clearer to understand but I have been reading a lot on methods and objects and I can't figure out what the actual differences are. Are set and get methods secure ways of entering values?
Let's start with what you think is the simpler code:
public class BuyAHouseInc
{
public void displayClient(String firstName, String surname, String address, int budget)
{
System.out.println("Client Name: " + firstName + " " + surname);
System.out.println("Address: " + address);
System.out.println("Budget: " + "€" + budget);
}
}
We could instantiate this class and use it like so:
public static void main(String[] args) {
BuyAHouseInc buyAHouseInc = new BuyAHouseInc();
buyAHouseInc.displayClient("jane", "doe", "123 main street", 100000);
}
The effect of this main method is to display the information on your screen. That's everything instances of this class can do. You can't share the information, or reuse it.
The first piece of code you show lets you create an object with fields that store data that you can reuse. The getters and setters are written so you can access those fields to use elsewhere in your program.
We can also add the displayClient method to this class, like so:
public class BuyAHouseInc {
private String firstName;
private String surname;
private String address;
private int budget;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
...
public void displayClient() {
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
}
So then I might be able to write a program like this:
public class Solution {
public static void main(String[] args) {
BuyAHouseInc jane = new BuyAHouseInc("jane", "doe", "123 main street", 100000);
BuyAHouseInc john = new BuyAHouseInc("john", "doe", "123 main street", 50000);
System.out.println("The following clients can afford to buy a house");
if (canAffordTheHouse(jane)) {
jane.displayClient();
}
if (canAffordTheHouse(john)) {
john.displayClient();
}
}
public static boolean canAffordTheHouse(BuyAHouseInc client) {
return client.getBudget() > 50000;
}
}
If you're asking about getter / setter vs direct access, then there are many advantages of getter / setter over direct access.
Basically:
It's more secure as variable implementations should be kept private
and non accessible by public sources.
It allows for additional functionality in the get / set call and
allowing different behavior for whom is getting / setting.
It allows for different access levels (public, protected, etc.)
It is, however, the exact same speed as accessing directly.
Here is another answer that shows what I said in more detail.
You could combine the blocks of code
public class BuyAHouseInc
{
// Instance variables
private String firstName;
private String surname;
private String address;
private int budget;
public void displayClient()
{
System.out.println("Client Name: " + this.firstName + " " + this.surname);
System.out.println("Address: " + this.address);
System.out.println("Budget: " + "€" + this.budget);
}
// method to set the first name in the object
public void setFirstName(String firstName)
{
this.firstName = firstName; // stores the first name
}
// method to retrieve the first name from the object
public String getFirstName()
{
return firstName; // return value of first name to caller
}
// method to set the surname in the object
public void setSurname(String surname)
{
this.surname = surname; // stores the surname
}
// method to retrieve the surname from the object
public String getSurname()
{
return surname; // return the value of surname to caller
}
// method to set the address in the object
public void setAddress(String address)
{
this.address = address; // stores the address
}
// method to retrieve the address from the object
public String getAddress()
{
return address; // return the value of address to caller
}
// method to set the budget in the object
public void setBudget(int budget)
{
this.budget = budget; // store the budget
}
// method to retrieve the budget from the object
public int getBudget()
{
return budget; // return the value of address to caller
}
}
Alternatively, you could pass a whole object of BuyAHouseInc into the display function.
public void displayClient(BuyAHouseInc b)
{
System.out.println("Client Name: " + b.getFirstName()+ " " + b.getSurname());
System.out.println("Address: " + b.getAddress());
System.out.println("Budget: " + "€" + b.getBudget());
}
public void displayClient(String firstName, String surname, String address, int budget)
{
//........
}
is simply another method. Enclosed in { and } defines what it does when a call to displayClient() method is called. displayClient() requires 3 arguments before it can perform it's task. The arguments are what's inside the () in public void displayClient(String firstName, String surname, String address, int budget). The 2nd piece of code can be put within the public class BuyAHouse block or { }. Your setters() and getters() are also similar to displayClient() but has fewer arguments.
What's inside { } of public class BuyAHouse are members or methods. These methods has access to the class variables
private String firstName;
private String surname;
private String address;
private int budget;
That's why on most of the syntax of setters(), you can see that it's setting/assigning/storing (whatever you like) values to your class variables. So basically set() methods are used to modify the value of the variables firstname, surname,address and budget
getters() are used to return the value of the variables.
For instance,
String name; //this has no string value yet
//function definition - you tell what you want this method to do
public void setMyName(String yourName){
name = yourName; //you store the value of yourName to name
}
//method call
setMyName("whatever name you like"); // whatever name you like will be passed to the yourName variable

Drive Tester for a Class Issues

I have been putting together a Drive Tester to test a class I have been working on for an assignment, but I have hit a dead end with the tester and I am not sure how to finish it up and remove any errors.
Here is the tester:
public class PersonTester
{
public static void main(String[] args)
{
System.out.println("PersonClassTester");
System.out.println("*****************");
System.out.println("");
Person joeSmith = new Person();
String "smith" = joeSmith.setSurName(); // All these statements with set surname and forname etc are apperantly not statements and require a semi-colon, even though they are there.
String "joe" = joeSmith.setForName();
int 25 = joeSmith.setAge();
double 1.57 = joeSmith.setHeight();
String "male" = joeSmith.setGender();
joeSmith.toString();
joeSmith.format();
}
}
The main issue with this is that the Netbeans client is stating that the setter statements highlighted are not actually statements, and are saying that it needs a semi-colon for each of them despite them actually being there. It is also saying that there are no formal or actual arguments. I know what they are but I'm getting confused on them regardless.
And this is the class I need to run through the tester:
public class Person
{
private String surName;
private String forName;
private int age;
private double height;
private String gender;
#Override
public String toString()
{
return getClass().getName() + "[surName= " + surName + " forName= " + forName + " age= " + age + " height= " + height + " gender " + gender + "]";
}
public void format()
{
System.out.format("%10s%10s%10d%10f%10s", surName, forName, age, height, gender);
}
public String getSurName()
{
return surName;
}
public String getForName()
{
return forName;
}
public int getAge()
{
return age;
}
public double getHeight()
{
return height;
}
public String getGender()
{
return gender;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public void setForName(String forName)
{
this.forName = forName;
}
public void setAge(int age)
{
this.age = age;
}
public void setHeight(double height)
{
this.height = height;
}
public void setGender(String gender)
{
this.gender = gender;
}
}
Any advice on getting the class tester to function properly? Once the tester works the rest of the assignment shouldnt be much of a problem.
Edit: The program compiles, but is unable to print the String statements.
PersonClassTester
*****************
surName forName 25 1.570000 gender
String "smith" = joeSmith.setSurName(); is not correct syntax. It should look like this:
joeSmith.setSurName("smith")
This tells Java to execute the method setSurName() on the object joeSmith, with the given string as an argument.
The same goes for the rest of your assignments in main.
Your setter method looks like:
public void setSurName(String surName)
{
this.surName = surName;
}
Which says your setter is not going to return anything and it expects one parameter which is of String type.
Now here's how you are using your setter method:
String "smith" = joeSmith.setSurName();
So here it means you are expecting a surname from setter which is one part of compiler error that you see. And as stated, it expects a string argument and you are not passing it and that's another part of compiler issue.
So you may want to change it to:
joeSmith.setSurName("smith");//similar changes with other setter method.
Which means, now you are passing string argument and not expecting anything in return by calling this method and hence Compiler would be happy with this.

toString : when does it return ClassName#HexValue, String Value associated with it

As per definition toString() returns "Returns a string representation of the object as:
getClass().getName() + '#' + Integer.toHexString(hashCode())
But sometimes I could see even if it is not Overriden in our class, it returns the String associated with it. I mean Object.toString() returns some String but not "ClassName#HexCode".
When does this happen. Please let me know whats the reason behind this ??
It's only possible if a class extends another class with overriden (or inherited overriden) toString().
The default behavior of toString() is to return the object as
getClass().getName() + '#' + Integer.toHexString(hashCode()).
But if you override toString() in base class or child class you can specify the way your object should be printed.
Probably in your case its using the inherited method of your base class .
Ex:
class Person {
private String myName; // name of the person
private int myAge; // person's age
private String myGender; // 'M' for male, 'F' for female
// constructor
public Person(String name, int age, String gender) {
myName = name;
myAge = age;
myGender = gender;
}
public String getName() {
return myName;
}
public int getAge() {
return myAge;
}
public String getGender() {
return myGender;
}
public void setName(String name) {
myName = name;
}
public void setAge(int age) {
myAge = age;
}
public void setGender(String gender) {
myGender = gender;
}
public String toString() {
return myName + ", age: " + myAge + ", gender: " + myGender;
}
}
public class Teacher extends Person {
//...
}
calling `toString();` method will call inherited `tOString()` method of base class and will return `return myName + ", age: " + myAge + ", gender: " + myGender;`

Categories