Usage of accessor methods - java

This is my class containing setters and getters
package Pack;
public class Details {
String FirstName,LastName,City,Country;
public Details(String firstName, String lastName, String city,
String country) {
super();
FirstName = firstName;
LastName = lastName;
City = city;
Country = country;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
===========================================================================
This is my main()
package Pack;
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Details d = new Details("Hari","L","Bangalore","India");
}
}
==========================================================================
I know my main() is incomplete. What should i write to display the contents of "d"?

There are two ways.
One, just print each property of your details object :
System.out.println("FirstName :"+d.getFirstName()); etc..
Or, a better option would be to override toString() method in your class
public void toString() {
return this.getFirstName()+ " " + this.getLastName()+" "+.... ;
}
and then just print your class System.out.println(d);

you need a toString() method in Details class:
public String toString(){
return this.firstName + " " + this.lastName + ", " + this.city + " " + this.country;
}
and
System.out.println(d.toString());
in main

Override toString() method in Details as follow and then just call to print what you want:
public String toString(){
return this.firstName+" "+this.lastName+" "+this.city+" "+this.country;
}
in main just call it as System.out.println(d);

Something like this?
System.out.printf("%s %s (%s, %s)\n", d.getFirstName(), d.getLastName(), d.getCity(), d.getCountry());
I would make your fields (FirstName, LastName, City, and Country) private, otherwise there's not much point in using getters and setters.

Try to add methods (or something similar with more properties):
public String asFirstnameLastname()
{
return firstName + " " + lastName;
}
public String asLastNameFirstname()
{
return lastName + " " + firstName;
}
toString() is also a good choice.

Related

How to get output objects on screen?

I am working on an assignment where I must instance several different objects and format them on the screen. I am having trouble getting the strings to output properly; in place of text I get an output like this
run:
First Name Last Name Student ID Number
studentdemo.StudentDemo#6d06d69c
studentdemo.StudentDemo#7852e922
studentdemo.StudentDemo#4e25154f
studentdemo.StudentDemo#70dea4e
studentdemo.StudentDemo#5c647e05
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my main
package studentdemo;
public class MainStudent {public static void main(String[] args) {
StudentDemo student1 = new StudentDemo("Peter\t","Adams\t","123546\t");
StudentDemo student2 = new StudentDemo("James\t","Clark\t","654332\t");
StudentDemo student3 = new
StudentDemo("Christopher\t","Colombo\t","223344\t");
StudentDemo student4 = new StudentDemo("Amy\t","Tan\t","997766\t");
StudentDemo student5 = new
StudentDemo("Marry\t","Madison\t","6543321\t");
System.out.println("First Name\t"+"Last Name\t"+"Student ID Number\t");
System.out.println(student1);
System.out.println(student2);
System.out.println(student3);
System.out.println(student4);
System.out.println(student5);
}
}
and here is my other class
package studentdemo;
public class StudentDemo {
private String firstName;
private String lastName;
private String studentIdNumber;
public StudentDemo(String firstName, String lastName, String
studentIdNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.studentIdNumber = studentIdNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setStudentIdNubmer(String studentIdNumber) {
this.studentIdNumber = studentIdNumber;
}
public String getStudentIdNumber() {
return studentIdNumber;
}
}
What am I doing wrong?`
This is because you are trying to print the object (student1) instead of the properties of object.
Please try:
System.out.println(student1.getFirstName()+"\t"+student1.getLastName()+"\t"+student1.getStudentIdNumber());
instead of:
System.out.println(student1);
Hope this will solve your problem.
You need to output like so:
System.out.println(student1.getFirstName() + " " + student1.getLastName());
A better solution would be to override the toString() method in your StudentDemo class. For example:
public class StudentDemo {
...
#Override
public String toString() {
return this.firstName + " " + this.lastName + " " + this.studentIdNumber;
}
}
Now when you create a new student object, ie StudentDemo student1 = new StudentDemo();, if you do System.out.prntln(student1);, the toString() method will automatically be called.

Creating a method where two objects are considered equal if the first and last names are the same.

So within this class, I need to create a Equals method that will check to determine if the two objects have the same name. I tried creating the two objects within the class and just initialize it with "" for the constructor, but it gave an error on the created objects
Person.Java
public class Person
{
String firstName = "";
String lastName = "";
String age = "";
public Person (String firstName, String lastName, String age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(String age){
this.age = age;
}
public String toString(){
return firstName + " " + lastName + ", " + age + " years old";
}
}
Here is my driver, so basically I need a method that sees both have the same name and prints out a message saying that they have the same name. My lab states it has to be in the class NOT the driver, which is why I'm lost considering I could easily make an if/else statement within the driver.
public class PersonDriver
{
public static void main(String[] args)
{
Person p1 = new Person("John","Doe", "42");
Person p2 = new Person("John","Doe", "43");
System.out.println(p1);
System.out.println(p2);
}
}

program calling default constructor? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Beginner here.
I cant get my head around why this code outputs the default halfway through. Can anyone take look?
sorry if the format is wrong, first time posting and will fix if not correct.
public class officemanager {
public static void main(String[] args) {
Staffmember aStaffMember = new Staffmember("Steven", "bob");
System.out.println(aStaffMember.toString());
Programmer appleprg = new Programmer("Marion", "bob", "Java");
appleprg.getLanguage();
System.out.println(appleprg.toString());
Doctor dr = new Doctor();
dr.setWard(5);
dr.setFirstName("ed");
dr.setLastName("fall");
System.out.println(dr.toString());
}
}
OUTPUT
Staffmember firstName=Steven, lastName=bob
Programmer firstName=Marion , lastName=bob language Java
default constructor
Doctor firstName=ed , lastName=fall Ward 5
Sorry guys here the class the default constructor is in. It is the Superclass called Staffmember and the firstname, lastname Strings are passed through it.
package oopinheritance;
public class Staffmember {
private String firstName;
private String lastName;
// default constructor
public Staffmember() {
System.out.println("default constructor");
}
// constructor
public Staffmember(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;}
public void setLastName(String lastName) {
this.lastName = lastName;}
public String toString() {
return "Staffmember firstName="
+firstName+ ", lastName=" + lastName;
}
}
Here is the Doctor class, it is a subclass of Staffmember and it has its own tostring method:
package oopinheritance;
public class Doctor extends Staffmember{
private int ward;
public int getWard() {
return ward;
}
public void setWard(int ward) {
this.ward = ward;
}
public String toString() {
return "Doctor firstName="
+this.getFirstName() + " , lastName=" + this.getLastName() + " \t
ward" + this.ward;
}
}
As you have not shown your whole program, so its hard to tell where is the error, but it might be in the default constructor of the doctor class.
Anyways here is the code that you can refer. It will give the correct output.
Here is the link you can refer to see the execution order
http://javabeginnerstutorial.com/learn-by-example-3/order-of-execution-of-blocks-in-java/
Java Constructors - Order of execution in an inheritance hierarchy
class GfG {
public static void main(String[] args) {
Staffmember aStaffMember = new Staffmember("Steven", "bob");
System.out.println(aStaffMember.toString());
Programmer appleprg = new Programmer("Marion", "bob", "Java");
appleprg.getLanguage();
System.out.println(appleprg.toString());
Doctor dr = new Doctor();
dr.setWard(5);
dr.setFirstName("ed");
dr.setLastName("fall");
System.out.println(dr.toString());
}
}
class Staffmember {
String firstName;
String lastname;
public Staffmember(String firstName, String lastname) {
super();
this.firstName = firstName;
this.lastname = lastname;
}
#Override
public String toString() {
return "Staff Member firstName=" + firstName + ", lastname=" + lastname;
}
}
class Programmer {
String firstName;
String lastName;
String Language;
public String getLanguage() {
return Language;
}
public void setLanguage(String language) {
Language = language;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Programmer(String firstName, String lastname, String Language) {
super();
this.firstName = firstName;
this.lastName = lastname;
this.Language = Language;
}
#Override
public String toString() {
return "Programmer firstName=" + firstName + ", lastName=" + lastName + ", Language=" + Language;
}
}
class Doctor {
int ward;
String firstName;
String lastName;
public void setWard(int ward) {
this.ward = ward;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastname) {
this.lastName = lastname;
}
public Doctor(int ward, String firstName, String lastName) {
super();
this.ward = ward;
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return "Doctor ward=" + ward + ", firstName=" + firstName + ", lastName=" + lastName;
}
}

Constructor requiring more than one for subclass super

Please help me find errors from this code. I'm still new and I don't know if this is correct or not.
I do have one error.
This is the error:
constructor Person in class Person cannot be applied to given types;
super();
^
required: String,String,String
found: no arguments
reason: actual and formal argument lists differ in length
This is my code:
import java.util.*;
public class Person {
//Data fields
private String lastName;
private String middleInitial;
private String firstName;
//Constructors
public Person(String lastName, String middleInitial, String firstName) {
this.lastName = lastName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
//Accessor methods
public String getlastName() {
return lastName;
}
public String getmiddleInitial() {
return middleInitial;
}
public String getfirstName() {
return firstName;
}
//Mutator methods
public void setlastName(String lastName) {
lastName = lastName;
}
public void setmiddleInitial(String middleInitial) {
middleInitial = middleInitial;
}
public void setfirstName(String firstName) {
firstName = firstName;
}
public String getName() {
String studentName = this.lastName + ", " + this.firstName +
this.middleInitial + ".";
return studentName;
}
} //end Person class
class Address {
//Data fields
private String streetName;
private int zipCode;
private String state;
private String country;
//Constructors
public Address(String streetName, int zipCode, String state,
String country) {
this.streetName = streetName;
this.zipCode = zipCode;
this.state = state;
this.country = country;
}
//Accessor methods
public String getstreetName() {
return streetName;
}
public int getzipCode() {
return zipCode;
}
public String getstate() {
return state;
}
public String getcountry() {
return country;
}
//Mutator methods
public void setstreetName(String streetName) {
streetName = streetName;
}
public void setzipCode(int zipCode) {
zipCode = zipCode;
//Integer.toString(zipCode);
}
public void setstate(String state) {
state = state;
}
public void setcountry(String country) {
country = country;
}
public String getAddress() {
String studentAddress = streetName + "\n" + state + ", " + country +
"\n" + zipCode;
return studentAddress;
}
} //end Address class
class Student extends Person {
private String dateOfBirth;
//Constructors
public Student (String studentName, String dateOfBirth) {
super();
dateOfBirth = dateOfBirth;
}
//Accessor methods
public String getdateOfBirth() {
return dateOfBirth;
}
//Mutator methods
public void setdateOfBirth() {
this.dateOfBirth = dateOfBirth;
}
public String toString() {
return ("Date of Birth: " + dateOfBirth);
}
} //end Student subclass
Edited: If I do so for both the Person and Address class. I can only have three-arg constructors. How can I call a one-arg constructor?
For example, I have
public Student (String firstName, String lastName, String middleInitial, String dateOfBirth) {
super(firstName, lastName, middleInitial); and
public Student (String streetName, String state, String country) {
super(streetName, state, country);
How can I get zipcode separately?
Class Person has a constructor, therefore the default no-arg constructor is not created for you. Therefore you can't call super() in Student's constructor, you have to call super(lastName, middleInitial, firstName);.
Or you could create a new Person no-arg constuctor.
Try this
In student class
public Student ( String lastName, String middleInitial, String firstName,String studentName, String dateOfBirth) {
super( lastName, middleInitial,firstName);
this.dateOfBirth = dateOfBirth;
}
Or
In Person class create no arg consructor. Eg:
public Person(){}
Person Class has a constructor with arguments. So default constructor will not be created. So you have to pass 3 String parameters in super(3 String parameters) or you have to create a constructor which does not take any parameter in person class.

How can I create an Address Book that can contain 100 Address Book Entries in java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is my class for Address Book Entry
public class AddressBookEntry {
private String firstname;
private String lastname;
private int streetno;
private String street;
private String city;
private int telephonenumber;
private String emailaddress;
public AddressBookEntry(String firstname, String lastname, int streetno,
String street, String city, int telephonenumber, String emailaddress) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.streetno = streetno;
this.street = street;
this.city = city;
this.telephonenumber = telephonenumber;
this.emailaddress = emailaddress;
}
public AddressBookEntry() {
// TODO Auto-generated constructor stub
}
THESE ARE THE SETTER-GETTER
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getTelephonenumber() {
return telephonenumber;
}
public void setTelephonenumber(int telephonenumber) {
this.telephonenumber = telephonenumber;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
THIS IS THE CUSTOM METHODS
public String fullName() {
return this.firstname + " " + this.lastname;
}
public String fullAddress() {
return this.streetno + " " + this.street + " st. " + this.city + " city";
}
public void displayAddress(){
System.out.println("Name : " + fullName());
System.out.println("Address : " + fullAddress());
System.out.println("Telephone Number : " + this.telephonenumber);
System.out.println("Email Address : " + this.emailaddress + "#gmail.com"+"\n");
}
}
NOW THIS IS THE CLASS FOR THE ADDRESSBOOK
import java.util.ArrayList;
import java.util.List;
public class AddressBook {
private List<AddressBookEntry> listOfEntries;
public AddressBook() {
this.listOfEntries = new ArrayList<>();
}
public void add(AddressBookEntry addressBookEntry) {
this.listOfEntries.add(addressBookEntry);
}
public void delete(int index) {
this.listOfEntries.remove(index);
}
public AddressBookEntry get(int index) {
return this.listOfEntries.get(index);
}
public AddressBookEntry[] viewAll() {
AddressBookEntry[] result = new AddressBookEntry[this.listOfEntries.size()];
this.listOfEntries.toArray(result);
return result;
}
}
How can I create a class address book that has a limit of 100 entries of AddressBookEntry objects using the given code above using arrays? While it includes a menu: AddEntry, DeleteEntry, ViewAllEntries, and UpdateEntry?
If you want fixed-sized you should use an array instead of List.
If for some reason you cannot change the list, you can provide the size to the ArrayList constructor.
public AddressBook() {
this.listOfEntries = new ArrayList<>(100);
}
However, you need to check the size before inserting the element.
public void add(AddressBookEntry addressBookEntry) {
if(this.listOfEntries.size() <= 100)
this.listOfEntries.add(addressBookEntry);
else
throw new IllegalStateException("Address book is full");
}

Categories

Resources