Implementing inheritance overriding the toString method - java

I have created a (Person,Student,Employee,Faculty and Staff)classes. Person has to subclasses Student and Employee.
Employee has two subclasses Faculty and Staff. I have done all the codings an they are working fine except my driver class TestPerson program its giving compilation errors
Note: A test program that Creates a Person,Student,Employee,Faculty,Staff, and invokes their toString Method.
The errors of driver class TestPerson.java are below:-
error: constructor Student in class Student cannot be applied to given types;
error: no suitable constructor found for Employee(String,String,String,String)
error: constructor Faculty in class Faculty cannot be applied to given types;
error: no suitable constructor found for Staff(String,String,String,String)"
**I am just providing the codes of the driver class. If you need my other codings of the other classes, please state in the comment, and I will immediately post it.
Please see my codings below:-
public class TestPerson {
public static void main(String[] args) {
Person person = new Person("John Doe", "123 Somewhere", "415-555-1212", "johndoe#somewhere.com");
Person student = new Student("Mary Jane", "555 School Street", "650-555-1212", "mj#abc.com", "junior");
Person employee = new Employee("Tom Jones", "777 B Street", "40-88-889-999", "tj#xyz.com");
Person faculty = new Faculty("Jill Johnson", "999 Park Ave", "92-52-22-3-333", "jj#abcxyz.com");
Person staff = new Staff("Jack Box", "21 Jump Street", "707-21-2112", "jib#jack.com");
System.out.println(person.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
System.out.println(faculty.toString() + "\n");
System.out.println(staff.toString() + "\n");
}
}
//Person Class
public class Person {
private String name;
private String address;
private String phone_number;
private String email_address;
public Person() {
}
public Person(String newName, String newAddress, String newPhone_number, String newEmail){
name = newName;
address = newAddress;
phone_number = newPhone_number;
email_address = newEmail;
}
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public void setAddress(String newAddress){
address = newAddress;
}
public String getAddress(){
return address;
}
public void setPhone(String newPhone_number){
phone_number = newPhone_number;
}
public String getPhone(){
return phone_number;
}
public void setEmail(String newEmail){
email_address = newEmail;
}
public String getEmail(){
return email_address;
}
public String toString(){
return "Name :"+getName();
}
}
//Student class
public class Student extends Person {
public final String class_status;
public Student(String name, String address, int phone, String email, String classStatus) {
super(name, address, phone, email);
class_status = classStatus;
}
public String toString(){
return "Student Status: " + super.getName();
}
}
//Employee Class
import java.util.Date;
public class Employee extends Person{
private String office;
private double salary;
private Date hire;
public Employee() {
}
public Employee(String name, String address, int phone, String email){
super(name, address, phone, email);
}
public Employee(String office, double salary, Date hire){
this.office = office;
this.salary = salary;
this.hire = hire;
}
public void setOffice(String office){
this.office = office;
}
public String getOffice(){
return this.office;
}
public void setSalary(double salary){
this.salary = salary;
}
public double getSalary(){
return this.salary;
}
public void setHire(Date hire){
this.hire = hire;
}
public Date getHire(){
return this.hire;
}
public String toString(){
return "Office " + super.getName();
}
}
//Faculty Class
public class Faculty extends Employee {
private String officeHours;
private int rank;
public Faculty(String name, String address, int phone, String email) {
super(name, address, phone, email);
}
public String toString(){
return "Office " + super.getOffice();
}
}
//Staff Class
public class Staff extends Employee {
private String title;
public Staff(String name, String address, int phone, String email) {
super(name, address, phone, email);
}
public Staff(String title){
this.title = title;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public String toString(){
return "Title :" + super.getName();
}
}

The reason you are getting those errors is that the constructors don't exist.
error: constructor Student in class Student cannot be applied to given
types; error: no suitable constructor found for
Employee(String,String,String,String)
That means you will not get the code to compile until you have this:
Student(String name, String addr, String phone, String email) {
....
}
Assuming you have set the properties in the constructor, toString would look like this:
public String toString() {
return this.name + "\n" + this.addr + "\n" + this.phone + "\n" + this.email;
}
UPDATE
Your problem is that Student has only this constructor:
public Student(String name, String address, int phone, String email, String classStatus)
Student needs a constructor which takes only four strings as its parameters. Alternatively, you can make everything take the five parameters you specified.

It's perhaps not related to the question itself, but I think the design could be refined like this:
define abstract class Role with the name of role
define classes Student, Employee, Staff whatever inheriting Role
define class Person with common properties for all person type, names etc, and having property of type Role inside
then define toString on Person and in all Role implementation
in this way you will be able to extend or modify Persons independently from Roles, which makes the design more flexible

The constructor of Person requires a String as third argument, but you are trying to pass int phone to the super-constructor in your sub-classes. That won't work because it's the wrong type.
By the way: you should always represent phone numbers with strings, not with integers.
It doesn't make sense to add or subtract phone numbers.
Integers don't allow leading zeros, which are used for area codes in some
countries.
Integers can't be larger than 2147483648. When you
try to store very long telephone numbers, this seemingly arbitrary
limit will cause very unexpected bugs.

First Set the Phone Number datatype as integer in all the classes ..
main Function will be:
public class TestPerson {
public static void main(String[] args) {
Person person = new Person("John Doe", "123 Somewhere", "415-555-1212",
"johndoe#somewhere.com");
Person student = new Student("Mary Jane", "555 School Street",
650-555-1212, "mj#abc.com", "junior");
Person employee = new Employee("Tom Jones", "777 B Street",
40-88-889-999, "tj#xyz.com");
Person faculty = new Faculty("Jill Johnson", "999 Park Ave",
92-52-22-3-333, "jj#abcxyz.com");
Person staff = new Staff("Jack Box", "21 Jump Street", 707-21-2112,
"jib#jack.com");
System.out.println(person.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
System.out.println(faculty.toString() + "\n");
System.out.println(staff.toString() + "\n");
}
}

Related

The field is not visible JAVA

I'm currently working on a program, and in my subclass, I need to have a no argument constructor that initializes the object with empty strings.
I've tried using super, I have setter and getter methods, but I keep getting "the field Person.name is not visible". I get this for address and phoneNumber as well.
How do I make it so it is visible, and I can initialize the objects without giving the constructor arguments? Please let me know if I'm doing anything wrong and need to fix something (:
// Create a class named Person
public class Person {
// Fields: name, address, and phone number. (2 points)
private String name;
private String address;
private String phoneNumber;
// No argument constructor that initializes the object with empty strings for name, address, and phone. (2 points)
public Person () {
super();
this.name = "";
this.address = "";
this.phoneNumber = "";
}
// 3 argument constructor that initializes the object with a name, address, and a phone number. (2 points)
public Person2 (String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
// Getter/setter methods for each of the fields. (3 points)
// set/get name
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
// set/get address
public void setAddress (String address) {
this.address = address;
}
public String getAddress () {
return this.address;
}
// set/get phone number
public void setPhoneNumber (String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber () {
return this.phoneNumber;
}
// toString method that returns a string for the name, address, and phone number (2 points)
// (you can override the toString method as part of a class which is pretty swag)
public String toString() {
return "Name: " + name + "\n" + "Address: " + address + "\n" + "Phone: " + phoneNumber;
}
}
// Create a subclass of Person named Customer
class Customer extends Person {
// A field for a customer number. (1 point)
private String customerNumber;
public Customer () {
// A no argument constructor that initializes the object with an empty string for the name, address, phone, and customer number. (2 points)
super(name, address, phoneNumber);
}
// A 4 argument constructor that initializes the object with a name, address, a phone number, and a customer number. (2 points)
public Customer2 (String name, String address, String phoneNumber, String customerNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.customerNumber = customerNumber;
}
// Getter/setter method for the customer number field. (1 point)
public void setCustomerNumber (String customerNumber) {
this.customerNumber = customerNumber;
}
// toString method that prints the information from the Person toString as well as the customer number (2 points)
public String toString() {
return "Name: " + name + "\n" + "Address: " + address + "\n" + "Phone: " + phoneNumber + "\n" + "Customer Number: " + customerNumber;
}
}
If a field is marked with private access then it can only be accessed from inside that class or instances of it. You should use the get methods. Or, you can get the result of toString and build on that.
Also, all constructors should have the same name as the class (no "2" added).
public class Person {
private String name;
private String address;
private String phoneNumber;
public Person() {
this("", "", "");
}
public Person(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
public void setAddress (String address) {
this.address = address;
}
public String getAddress () {
return this.address;
}
public void setPhoneNumber (String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber () {
return this.phoneNumber;
}
#Override
public String toString() {
return "Name: " + name + "\n" + "Address: " + address + "\n" + "Phone: " + phoneNumber;
}
}
// Create a subclass of Person named Customer
class Customer extends Person {
private String customerNumber;
public Customer () {
this("", "", "", "");
}
public Customer (String name, String address, String phoneNumber, String customerNumber) {
super(name, address, phoneNumber);
this.customerNumber = customerNumber;
}
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber (String customerNumber) {
this.customerNumber = customerNumber;
}
#Override
public String toString() {
return super.toString() + "\n" + "Customer Number: " + customerNumber;
}
}
You cannot access or assign to a private field in any other class than the one that it is declared in.
You cannot declare a constructor with any name other than the name of the class. Thus Person2 and Customer2 are not neither valid constructors or valid methods. (A method requires a return type!)
A constructor must explicitly (via a super call) or implicitly chain a no-args constructor in its superclass.
Basically, your choices for initializing a private field in a superclass are either use a super(...) call to chain the a superclass constructor passing the value OR call a superclass setter method within the subclass constructor.
For example, the 4 arg constructor in Customer could be:
public Customer (String name, String address,
String phoneNumber, String customerNumber) {
super(name, address, phoneNumber);
this.customerNumber = customerNumber;
}
or
public Customer (String name, String address,
String phoneNumber, String customerNumber) {
super(); // you could leave this out - it is implied
setName(name);
setAddress(address);
setPhoneNumber(phoneNumber);
this.customerNumber = customerNumber;
}
IMO, the former is better. It is more concise and more readable.
The toString() method in Customer cannot refer directly to the private fields of the Person. It could use the fields' getters.
I don't think there is any actual need to call the super constructor in the person class. However, in the constructor for the costumer class, you should just call the super constructor with no arguments.
Edit: or you could initiate the values directly upon declaration, like the guy above me said.
PS. kinda unrelated, but, you could have one constructor but give the arguments default values. So you can call it with and without arguments with no need to override it.
There are a few issues in the snippet that you provided:
There is no need to define different names for constructors of the same class. The fact that their signature (i.e. set of input parameters) is different suffices.
Regarding your question, the error is that you're trying to access Person's private fields in the Customer's constructors directly. There are two ways to fix this issue:
Change the Person fields' scope from private to protected. This will allow any class that inherits the Person class to access the aforementioned fields directly.
When in Customer class, use the getter/setter methods to access the private fields.

Java working with superclasses, but I do not get the output I expect

Hi I have written this program that Implements a superclass Employee that has the following fields and methods.
Fields:
String firstName
String lastName
int employeeID
double salary
Methods:
Constructor(): initialize balance field to null and zero.
Setters and getters for firstName, lastName, and employeeID
EmployeeSummary() – prints all account attributes
Part 2: Implement a Manager class that inherits from the Employee class.
Has a department attribute
Methods:
EmployeeSummary() – prints all superclass and subclass attributes
The problem is I expected to see:
Employee Name: Charles Dickens Employee Id : 34599 salary: 6500.0
Department : Accounts
as the output but I get nothing....
Any help is greatly appreciated.
here is the code:
package week1john_huber;
import java.util.*;
import java.lang.*;
import java.io.*;
class Employee {
//attributes of Employee class
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee() { //default constructor
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.0;
}
public void setFirstName(String fname) { //set and get methods for all attributes
firstName = fname;
}
public String getFirstname() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lname) {
lastName = lname;
}
public double getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int empId) {
employeeID = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double s) {
salary = s;
}
public void EmployeeSummary() { //display all attributes of Employee
System.out.println("Employee Name: " + firstName + " " + lastName + " Employee Id :" + employeeID + " salary: " + salary);
}
}
class Manager extends Employee {
private String department;
public Manager() { //default constructor
super(); //calling superor base class default constructor
department = null;
}
public String getDepartment() {
return department;
}
public void setDepartment(String dept) { //set and get methods for department
department = dept;
}
public void EmployeeSummary() {
super.EmployeeSummary(); //calling super class method with same name
System.out.println("Department : " + department);
}
}
class TestEmployee {
public static void main(String[] args) {
Manager mgr = new Manager();
mgr.setFirstName("Charles"); //all set methods of super class are available to derived class
mgr.setLastName("Dickens");
mgr.setEmployeeID(34599);
mgr.setSalary(6500);
mgr.setDepartment("Accounts");
mgr.EmployeeSummary();
}
}
Ok, I believe the problem is the fact that you have the whole thing in a single file.
Try moving the TestEmployee class to its own file and rename the class to
public class TestEmployee
It should work that way.

Constructor + Inheritance support

I am fairly new to Inheritance, and I'm not sure if I am doing it right but I seem to be on the right track. The program runs fine except the output I am getting isn't right. I think the problem is to do with my constructors.
public class Person {
protected static String name;
protected static int birthYear;
public Person(String name, int birthYear) {
}
public String name (String n) {
n = name;
return n;
}
public int birthYear (int bY) {
bY = birthYear;
return bY;
}
#Override
public String toString() {
return String.format(name + birthYear);
}
}
public class Student extends Person {
protected String major;
public Student(String name, int birthYear, String major) {
super(name, birthYear);
major = "";
}
public String major(String maj) {
maj = major;
return maj;
}
public String toString() {
super.toString();
return super.toString() + major;
}
}
public class Instructor extends Person {
protected static int salary;
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
salary = 0;
}
public int salary(int sal) {
sal = salary;
return sal;
}
public String toString() {
super.toString();
return super.toString() + salary;
}
}
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Perry", 1959);
Student s = new Student("Sylvia", 1979, "Computer Science");
Instructor e = new Instructor("Edgar", 1969, 65000);
System.out.println(p);
System.out.println("Expected: Person[name=Perry,birthYear=1959]");
System.out.println(s);
System.out.println("Expected:" +
"Student[super=Person[name=Sylvia,birthYear=1979],major=Computer]");
System.out.println(e);
System.out.println("Expected:" + "Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]");
}
}
OUTPUT I AM GETTING:
null0
Expected: Person[name=Perry,birthYear=1959]
null0null
Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]
null00
Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]
Try changing your constructor in Person to:
public Person(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Currently, the constructor has an empty body, so when you call super(name, birthYear); in the subclass constructor, nothing actually happens.
Your Student constructor also has an error. You forgot to initialize the major field.
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
You have the same problem in the Instructor constructor...
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
this.salary = salary;
}
Finally, you need to take away the static keywords before the fields in Person. This is because static ensures, that there will always be one (and only one) instance of those fields per class, as opposed to one per instance, like you want it to be:
protected String name;
protected int birthYear;
Same thing for the salary field in Instructor.
n = name; this causing your problem. It must be name = n;. All your setter function contain this problem, correct them all and tell me result.

Java, calling methods and override

I have to design a class that consists of 2 subs-classes. Let's say A and B and B has 2 subs-classes too. This part is really not important because I did all this with different names.
I am struggling with trying to run my code. I have the code but I am getting 2 errors. I can't figure out how to fix it.
The errors are the following:
aaa1.java:147: cannot find symbol
symbol : constructor Employee(java.lang.String,java.lang.String,java.lang.String,java.lang.String)
location: class Employee
super(name, address, phone, email);
^
aaa1.java:179: cannot find symbol
symbol : constructor Employee(java.lang.String,java.lang.String,java.lang.String,java.lang.String)
location: class Employee
super(name, address, phone, email);
My code:
import java.util.*;
public class aaa1 {
public static void main(String[] args){
Person p = new Person("J11h", "123 ABC St", "908-123-456", "asdf123#gmail.com");
Student s = new Student("222se1h", "123 ABC St", "908-123-456", "asdf123#gmail.com", 1);
Date date = new Date();
Employee e = new Employee("wewesh", "123 ABC St", "908-123-456", "asdf123#gmail.com", "123", 2000.00, date);
Faculty f = new Faculty("eewrr", "123 ABC St", "908-123-456", "asdf123#gmail.com", "1pm - 3pm", "Head of the department");
Staff st = new Staff("rrereh", "123 ABC St", "908-123-456", "asdf123#gmail.com", "Assistant");
System.out.println(p.toString());
System.out.println(s.toString());
System.out.println(e.toString());
System.out.println(f.toString());
System.out.println(st.toString());
}
}
class Person {
//A person has a name, address, phone number, and email address.
String name;
String address;
String phone;
String email;
public Person(String name, String address, String phone, String email) {
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
//Overriding
public String toString(){
return "The person's information is "+name+ ", " +address+ ", " +phone+ ", " +email;
}
}
class Student extends Person{
//A student has a class status
//(freshman,sophomore, junior, or senior).
//Define the status as a constant.
final int freshman =1;
final int sophomore =2;
final int junior=3;
final int senior=4;
int status;
public Student(String name, String address, String phone, String email, int status) {
super(name, address, phone, email);
this.status = status;
}
public int getStatus(){
return status;
}
public void setStatus(int status){
this.status = status;
}
//Overriding
public String toString(){
return "The student's information is: " +super.toString()+ "," + status;
}
}
class Employee extends Person{
//An employee has an office, salary, and date hired.
String office;
double salary;
java.util.Date dateHired;
public Employee(String name, String address, String phone, String email, String office, double salary, Date dateHired){
super(name, address, phone, email);
this.office = office;
this.salary = salary;
this.dateHired = dateHired;
}
public String getOffice(){
return office;
}
public void setOffice(String office){
this.office = office;
}
public double getSalary(){
return salary;
}
public void setSalary(double salary){
this.salary = salary;
}
public void setDateHired(Date dateHired){
this.dateHired = dateHired;
}
//Overriding
public String toString(){
return "The Employee's information is: " +super.toString()+ ", " +office+ ", " +salary+ ", " +dateHired;
}
}
class Faculty extends Employee{
//A faculty member has office hours and a rank.
String officeHours;
String rank;
public Faculty(String name, String address, String phone, String email, String officeHours, String rank){
super(name, address, phone, email);
this.officeHours = officeHours;
this.rank = rank;
}
public String getOfficeHours(){
return officeHours;
}
public void setOfficeHours(String officeHours){
this.officeHours = officeHours;
}
public String getRank(){
return rank;
}
public void setRank(String rank){
this.rank = rank;
}
//Overriding
public String toString(){
return "The faculty's information is: " +super.toString()+ ", " + officeHours + ", " + rank;
}
}
class Staff extends Employee{
//A staff member has a title
String title;
public Staff(String name, String address, String phone, String email, String title){
super(name, address, phone, email);
this.title = title;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
//Overriding
public String toString(){
return "The staff's information is: " +super.toString()+ "," + title;
}
}
Can you please help me?
Your Employee class contains a constructor with the following parameters:
public Employee(String name, String address, String phone, String email, String office, double salary, Date dateHired){
And your Faculty and Staff classes, which extend Employee, contain this explicit call to super:
super(name, address, phone, email);
The number of arguments in the call to super and the number of arguments in the Employee class constructor do not match; you're providing four String arguments when it needs one additional String, a double, and a java.util.Date.
Faculty - the class at line 147 - extends Employee, so you need to invoke a super constructor from Employee:
public Employee(String name, String address, String phone, String email, String office, double salary, Date dateHired){
i.e. you need to pass all of these parameters if you want to instantiate a subclass of Employee such as Faculty.
Alternatively, you could declare another constructor in Employee which takes just those 4 parameters. However, you would then need to decide what to do about the parameters that you have not passed in - do you simply set them to null, or do you set them to a safe default? This depends upon your application.
I believe that as you have it extending you need to also include the original constructor, so you have to have the same constructor as a person in the student staff and employee (with an #Override )
even if it just calls super();
so that is a Constructor (string,string,string,string);
Employee(java.lang.String,java.lang.String,java.lang.String,java.lang.String)
You will find the problem if you think a while of:
What will be the office, salary and hired date for a Faculty or a Staff member?

Inner classes, wrong output

I'm just going through inner classes but I'm getting the wrong output.
I'm basically trying to create a student object with two different addresses using an address class but I'm getting some ridiculous output. I'm clearly doing something completely wrong so if anyone could help that would be brilliant.
Student class:
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet, int uniNumber, String uniStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
uniAddress = new Address(uniNumber, uniStreet);
}
public void setUniAddress (Address uniAddress){
this.uniAddress = uniAddress;
}
public class Address {
public int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
}
public String toString() {
String a = name + "\n" + homeAddress + " " + uniAddress;
return a;
}
}
and my test student class to create the object and to run the toString:
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("Cathy", 21, "Smithfield Drive", 72, "Nottingham Drive");
Student.Address anotherAddress
= s1.new Address(8, "Deerfield Way");
System.out.println(s1.toString());
}
the output i'm getting is: Cathy
student.Student$Address#2760e8a2 student.Student$Address#4b48f7e0
Thanks
If you want nice output instead of something like Cathy student.Student$Address#2760e8a2, then you need to override the toString() method in your class Address.
Currently, the toString() method that you have is in class Student, not in class Address - carefully check the { and }.
You need to implement the toString()-Method of Adress as well.
public class Address {
public int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
public String toString() {
return street + Integer.valueOf(number);
}

Categories

Resources