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);
}
Related
I'm trying to call method within the BasicInfo class (full name(), alsoKnownAs()) into another class called Customer, specifically within the displayInfo() portion, but am not sure how to do that, here is my code:
enum Gender {MALE, FEMALE}
class BasicInfo
{
private String firstName, secondName, lastName;
private Gender g;
//Default Constructor
public BasicInfo()
{
//Do nothing
}
//Other Constructor
public BasicInfo(String firstName, String secondName, String lastName, Gender g)
{
this.firstName = firstName;
this.secondName = secondName;
this.lastName = lastName;
this.g = g;
}
//Copy Constructor
public BasicInfo(BasicInfo bi)
{
this.firstName = bi.firstName;
this.secondName = bi.secondName;
this.lastName = bi.lastName;
this.g = bi.g;
}
public String getFirstName()
{
return firstName;
}
public String getSecondName()
{
return secondName;
}
public String getLastName()
{
return lastName;
}
private Gender getGender()
{
return g;
}
public void setInfo(String firstName, String secondName, String lastName, Gender g)
{
this.firstName = firstName;
this.secondName = secondName;
this.lastName = lastName;
this.g = g;
}
private String fullName()
{
return (firstName + " " + secondName + " " + lastName);
}
private String alsoKnownAs()
{
return (firstName.charAt(0) + ". " + secondName.charAt(0) + ". " + lastName);
}
public void displayInfo()
{
System.out.printf("Full name: %s%n", fullName());
System.out.printf("Also known as: %s%n", alsoKnownAs());
System.out.printf("Gender: %s%n", getGender());
}
}
class Customer
{
private BasicInfo bi;
private int birthYear;
public Customer()
{
//Do nothing
}
public Customer(BasicInfo bi, int birthYear)
{
this.bi = bi;
this.birthYear = birthYear;
}
public Customer(Customer c)
{
this.bi = c.bi;
this.birthYear = c.birthYear;
}
public BasicInfo getBasicInfo()
{
return bi;
}
public int getBirthYear()
{
return birthYear;
}
public void setInfo(BasicInfo bi, int birthYear)
{
this.bi = bi;
this.birthYear = birthYear;
}
public void displayInfo()
{
System.out.printf("Full name: %s%n", bi.fullName());
System.out.printf("Also known as: %s%n", bi.alsoKnownAs());
System.out.printf("Gender: %s%n", bi.getGender());
System.out.printf("Year of birth: %d%n", birthYear);
}
}
Within customer class, displayInfo(), I used "bi.fullName()" and "bi.alsoKnownAs()" and "bi.getGender()", is this the right way to method call? Any help would be greatly appreciated :)
I tried using "BasicInfo.'the method'" as well, but still resulted in a compilation error.
This is against Java principles. If a method is designed to be called outside of its class then it cannot be private.
You should change access specifier of this methods to protected/public or default as the private method can be accessed only within the current class.
Thanks everyone for taking the time to read my post.
public void displayInfo()
{
System.out.printf("Full name: %s%n", bi.fullName());
System.out.printf("Also known as: %s%n", bi.alsoKnownAs());
System.out.printf("Gender: %s%n", bi.getGender());
System.out.printf("Year of birth: %d%n", birthYear);
}
I changed the above to this:
public void displayInfo()
{
bi.displayInfo();
System.out.printf("Year of birth: %d%n", birthYear);
}
Which displayed the information from the BasicInfo class's displayInfo() method. Perhaps my question wasn't very clear in the first place. Instead of asking how to access a private method, I should have asked how to call displayInfo() method from the BasicInfo class into the Customer class.
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 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
I have code like this:
public class Main {
public static void main(String[] args) {
List<Object> arrayList = new ArrayList<Object>();
arrayList.add(new Student("First", "Last", "10"));
System.out.println(arrayList);
}
}
With Student Class is:
public class Student extends Human {
private String grade;
public Student(String first, String last, String gradeValue) {
super(first, last);
this.setGrade(gradeValue);
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
It's will extends from Human Class:
public abstract class Human {
private String firstname;
private String lastname;
public Human(String first, String last) {
this.setFirstname(first);
this.setLastname(last);
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
}
Main ideas is I try to create a list 10 students with FirstName LastName and Grade.
Now when I try to print the list in main method, it's show me this: [Student#6fbae5f5].
What I want it show is: First Last 10.
Please note that I try to add more student to the list and it have to show like this:
FirstName1 LastName1 10
FirstName2 LastName2 3
FirstName3 LastName3 7
......................
Add below code in your Student class
#Override
public String toString() {
return "Student [getFirstname()=" + getFirstname() + ", getLastname()="
+ getLastname() + ", getGrade()=" + getGrade() + "]";
}
Since each object has toString() method, the default is displaying the class name representation, then adding # sign and then the hashcode. In your case, you're printing the object itself.
If you want to print the content of the arrayList, you should loop on it:
for(Student student : arrayList) {
System.out.println(student)
}
That's after you'll override toString in Student.
1.Add this to Human Class:
#Override
public String toString() {
// TODO Auto-generated method stub
return firstname + " " + lastname;
}
2. Add this to Student Class:
#Override
public String toString() {
// TODO Auto-generated method stub
return super.toString() + " " + grade;
}
Here is the class:
package employee;
public class Employee
{
private String name, department,position;
private int idNumber;
public Employee(String n, int id, String depart,String pos)
{
n= name;
id=idNumber;
depart=department;
pos=position;
}
public Employee(String n, int id)
{
n= name;
id=idNumber;
department="";
position="";
}
public Employee()
{
name="";
idNumber=0;
department="";
position="";
}
public void setName(String n)
{
n=name;
}
public void setDepartment(String depart)
{
depart=department;
}
public void setPosition(String pos)
{
pos=position;
}
public void setId(int id)
{
id=idNumber;
}
public String getName()
{
System.out.println();
return name;
}
public String getDepartment()
{
return department;
}
public String getPosition()
{
return position;
}
public int getId()
{
return idNumber;
}
}
Here is the program:
package employee;
public class RunEmployee
{
public static void main(String[] args)
{
Employee first= new Employee();
first.setName("Susan Myers");
first.setId(47899);
first.setDepartment("Accounting");
first.setPosition("Vice President");
Employee sec= new Employee("Mark Jones",39119,"IT","Programmer");
Employee third= new Employee("Joy Rogers", 81774);
third.setDepartment("Manfacturing");
third.setPosition("Engineer");
/*Printing employee ones information*/
System.out.print("Employee #1- using the no-arg constructor.");
System.out.println("Name: " + first.getName());
System.out.println("Id Number: "+ first.getId());
System.out.println("Department: " + first.getDepartment());
System.out.println("Position: "+ first.getPosition());
/*Printing employee twos information*/
System.out.println("Name: " + sec.getName());
System.out.println("Id Number: "+ sec.getId());
System.out.println("Department: " + sec.getDepartment());
System.out.println("Position: "+ sec.getPosition());
/*Printing employee threes information*/
System.out.print("Employee #3- using a constructor that accepts the name"
+ "and ID number only.");
System.out.println("Name: " + third.getName());
System.out.println("Id Number: "+ third.getId());
System.out.println("Department:" + third.getDepartment());
System.out.println("Position: "+ third.getPosition());
}
}
For this project, I am simply trying to store values into the constructor in different ways. However, my output is showing that my mutator methods are not storing any values. I tried to post my output but I do not have the reputation points. Basically, all the the values for the things I tried to arguments say zero or null.
You've got your assignments backwards!
n = name; puts the value of name to n, not the other way around.
You are assigning the value from the Employee instance to your passed in parameters. To prevent that, it is probably a good idea to use this -
this.name = n; // <-- assign n to the name field of the current instance.
In your example code, this.n would have given you a compile time error.