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
Related
I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class
I've just learned about superclasses and subclasses and the homework is pretty simple: have 2 classes and a test class to call and print the attributes. Below is my code from all 3 classes. My question is, why isn't the department attributes printing in my main? Everything else prints just fine, I just can't get that last little bit to print. I think it has something to do with super...thank you in advance! Second computer course and I'm finally feeling I sort of get it, so that's improvement from the first class I took!
public class Employee {
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee () {
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.00;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getEmployeeID() {
return employeeID;
}
public double getSalary() {
return salary;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " + getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
return employeeSummary;
}
}
public class Manager extends Employee {
private String departmentA;
public Manager() {
super();
departmentA = null;
}
public String getDepartmentA() {
return departmentA;
}
public void setDepartmentA(String departmentA) {
this.departmentA = departmentA;
}
public void EmployeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
}
public class ManagerDerivation {
public static void main(String[] args) {
Manager person = new Manager();
person.setFirstName("Ron");
person.setLastName("Weasley");
person.setEmployeeID(2345);
person.setSalary(65000.00);
person.setDepartmentA("Department of Magical Law Enforcement");
person.employeeSummary();
return;
}
}
Method names are case sensitive. EmployeeSummary() does not override employeeSummary() because it uses a different name.
To avoid mistakes like this, always include the #Override annotation on overridden methods. If you include that annotation and make a mistake in the method signature, compilation will fail.
Note also that your return types for the two methods are different (String and void). Overridden methods must have compatible return types.
There is some spelling (employeeSummary vs. EmployeeSummary) mistakes and return types dont match, in Employee should be
public void employeeSummary () {
String employeeSummary = "Employee's name is: " + getFirstName() + " " +
getLastName() +
". The employee's ID number is " + getEmployeeID() +
". The employee's salary is " + getSalary();
System.out.println(employeeSummary);
}
then in Manager
public void employeeSummary() {
super.employeeSummary();
System.out.println("The employee's department is " + departmentA);
}
I am new to using Java - so please forgive my ignorance. Would you be able to look at this code and let me know why I get error:
cannot find symbol - variable
when I call the constructor method. I am using BlueJ. Basically I put in the variables and then hit ok to create an object but it comes up with that error.
/**
* Write a description of class Membership here.
*
* #author (Gohar Warraich)
* #version (1.0)
*/
public class Membership
{
// instance variables - replace the example below with your own
private String firstname;
private String lastname;
private String phonenumber;
private int idnumber;
/**
* Constructor for objects of class Membership
*/
public Membership(String newfirstname, String newlastname, String newphonenumber, int newidnumber)
{
// initialise instance variables
firstname = newfirstname;
lastname = newlastname;
phonenumber = newphonenumber;
idnumber = newidnumber;
}
/**
* Accessor method of Membership
*/
public String getfirstname()
{
return firstname;
}
public String getlastname()
{
return lastname;
}
public String getphonenumber()
{
return phonenumber;
}
public int getidnumber()
{
return idnumber;
}
/**
* Mutator method of Membership
*/
public void setfirstname(String insertfirstname)
{
firstname = insertfirstname;
}
public void setlastname(String insertlastname)
{
lastname = insertlastname;
}
public void setphonenumber(String insertphonenumber)
{
phonenumber = insertphonenumber;
}
public void setid(int insertidnumber)
{
idnumber = insertidnumber;
}
public void printMembership()
{
System.out.println("The firstname is " + firstname + " The lastname is " + lastname +" The phoneNumber is "+ phonenumber +" The idNumber is " +idnumber);
}
}
#gohar, There isn't a problem in this code. It must be in your call to the constructor. I'll give you an example of what this should look like.
Membership membershipName = new Membership ("String", "String", "String", 0101)
0101 can be any int, and you can name the variable what ever you want by changing membershipName. Hope this helps. :)
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.
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!