Constructors from extended class in Java - java

I'm having some trouble with a hw assignment. In one assignment, we had to create a Person class. Mine was:
public class Person
{
String firstName;
String lastName;
String telephone;
String email;
public Person()
{
firstName = "";
lastName = "";
telephone = "";
email = "";
}
public Person(String firstName)
{
this.firstName = firstName;
}
public Person(String firstName, String lastName, String telephone, String email)
{
this.firstName = firstName;
this.lastName = lastName;
this.telephone = telephone;
this.email = email;
}
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 getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) {
return true;
}
// must return false if the explicit parameter is null
if (otherObject == null) {
return false;
}
if (!(otherObject instanceof Person)) {
return false;
}
Person other = (Person) otherObject;
return firstName.equals(other.firstName) && lastName.equals(other.lastName) &&
telephone.equals(other.telephone) && email.equals(other.email);
}
public int hashCode()
{
return 7 * firstName.hashCode() +
11 * lastName.hashCode() +
13 * telephone.hashCode() +
15 * email.hashCode();
}
public String toString()
{
return getClass().getName() + "[firstName = " + firstName + '\n'
+ "lastName = " + lastName + '\n'
+ "telephone = " + telephone + '\n'
+ "email = " + email + "]";
}
}
Now we have to create a Loan class that uses Person as an attribute, and then extend that Loan class. My Loan class is:
public abstract class Loan
{
public void setLoanId(int nextId)
{
loanId = nextId;
nextId++;
}
public int getLoanId()
{
return loanId;
}
public void setInterestRate(double interestRate)
{
this.interestRate = interestRate;
}
public double getInterestRate()
{
return interestRate;
}
public void setLoanLength(int loanLength)
{
this.loanLength = loanLength;
}
public int getLoanLength()
{
return loanLength;
}
public void setLoanAmount(double loanAmount)
{
this.loanAmount = loanAmount;
}
public double getLoanAmount(double loanAmount)
{
return loanAmount;
}
public void printPayments()
{
double monthlyInterest;
double monthlyPrincipalPaid;
double newPrincipal;
int paymentNumber = 1;
double monthlyInterestRate = interestRate / 1200;
double monthlyPayment = loanAmount * (monthlyInterestRate) /
(1 - Math.pow((1 + monthlyInterestRate),( -1 * loanLength)));
// amortization table
while (loanAmount != 0) {
monthlyInterest = loanAmount * monthlyInterestRate;
monthlyPrincipalPaid = monthlyPayment - monthlyInterest;
newPrincipal = loanAmount - monthlyPrincipalPaid;
loanAmount = newPrincipal;
System.out.println("Payment Number | Interest | Principal | Loan Balance");
System.out.printf("%d, %.2f, %f, %f", paymentNumber++, monthlyInterest, newPrincipal, loanAmount);
}
}
/*
//method to print first payment
public double getFirstPayment()
{
}
method to print last payment
public double getLastPayment()
{
}*/
private Person client;
private int loanId;
private double interestRate;
private int loanLength;
private double loanAmount;
private static int nextId = 1;
}
And then extended the Loan class with CarLoan class, there is a function prototype of:
public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax,
double interestRate, CAR_LOAN_TERMS length)
I'm confused on how I use the Person constructor from the superclass. I cannot necessarily do
super(client);
in my constructor which is what the book did with some primitive types in their example. Not sure what the correct thing to do is... Any thoughts? Thanks!

CarLoan should not extend Person. That makes no sense since a CarLoan can't be a Person.
But Person can be a class variable in the CarLoan class.
public class CarLoan {
private Person client;
private double vehiclePrice;
public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) {
this.client = client;
this.vehiclePrice = vehiclePrice;
..
}
}

It looks like you want to be using composition in stead of inheritance.
In plain english, a CarLoan has a client (of type Person). A CarLoan itself is not a Person (which inheritance would suggest).
So you should do what Espen suggests (composition), in stead of CarLoan extends Person (inheritance).
A possibly legit use of inheritance would be:
class Waiter extends Person {
String employeeId;
// A waiter is a person with some extra information
public Waiter(String firstName, String lastName, String telephone,
String email, String employeeId) {
super(firstName, lastName, telephone, email); // must be first
this.employeeId = employeeId;
}
}

If CarLoan is to extend Person, then Person becomes the superclass of CarLoan.
From within the constructor of CarLoan you must always call one of the Person constructors via the super keyword before any other processing takes place.
However, it seems to me very much like you must be confused, as your prototype method passes an instance of Person to CarLoan. Further, I cannot see why a class called CarLoan would extend a person.

Related

Calling a private method within another class into a class

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.

How to get rid of syntax error on token "public" in main class?

I am getting a syntax error in my main class when I call the constructor from another class that I need for the main program to run. This program is focused on inheritance and the appropriate calling of constructors and arguments. This is the error message I get during compilation:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "public", record expected after this token
at a6main.main(a6main.java:7)
This is the line of code that is causing the error:
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
"2000", true, "1000");
The rest of the code can be found below:
class person {
String Name;
String Address;
String Telephone;
person (String Name, String Address, String Telephone) {
this.Name = Name;
this.Address = Address;
this.Telephone = Telephone;
}
String getName() {
return Name;
}
String getAddress() {
return Address;
}
String getTelephone() {
return Telephone;
}
void setName(String Name) {
this.Name = Name;
}
void setAddress(String Address) {
this.Address = Address;
}
void setTelephone(String Telephone) {
this.Telephone = Telephone;
}
}
public class customer extends person {
String number;
boolean OnMailingList;
//constructor and getters and setters
customer (String Name, String Address, String Telephone, String number, boolean OnMailingList) {
//inherit persons information
super(Name, Address, Telephone);
this.number = number;
this.OnMailingList = OnMailingList;
}
String getnumber() {
return number;
}
void setnumber(String number) {
this.number = number;
}
boolean OnMailingList () {
return OnMailingList;
}
void setOnMailingList(boolean OnMailingList) {
this.OnMailingList = OnMailingList;
}
}
public class PreferredCustomer extends customer {
private int purchase;
double discount;
/**public constructor so its accessible to main
* else ifs for certain percentage of discounts
* getters and setters for purchase and discount
* super to inherit other features from other classes */
public int getpurchase() {
return purchase;
}
public double getdiscount () {
return this.discount;
}
public void setPurchase(int purchase) {
this.purchase = purchase;
}
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur,
boolean OnMailingList, double Discount, PreferredCustomer preferredCustomer) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
preferredCustomer.discount = discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
}
public class a6main {
public static void main (String [] args) {
public PreferredCustomer() {
}
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821","2000", true, "1000");
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
}
You have several mistakes here. I've corrected them, and the program launches, providing the result:
Name: Al
Address: 222BurdSt
Telephone number: 2102223321
Customer ID: 46821
Amount spent: 2000
On mailing list: true
Discount: 10.0
Remove PreferredCustomer constructor from the main method. It can't be a part of a
method, it is a part of a class. Then, the constructor for PreferredCustomer is already present in PreferredCustomer class.
Hopefully, your customer and PreferredCustomer classes are in separate files? If not, put them in separate files named customer.java and PreferredCustomer.java. In PreferredCustomer class constructor, remove PreferredCustomer preferredCustomer from arguments. It's redundant: why you need to pass one customer into another? Do customers have any relationships with each other? Now the number of arguments will match when you call the constructor (and don't use strings "2000", "1000" where should be integers):
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
2000, true, 1000);
Further in the PreferredCustomer constructor, use this instead of preferredCustomer here: this.discount = Discount; and print Discount with upper case, as in the signature of the constructor.
As a result, the code of the constructor should be:
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur, boolean OnMailingList, double Discount) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
this.discount = Discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
The main method in a6main class:
public static void main (String [] args) {
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821", 2000, true, 1000);
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
And take care of naming conventions, as other people pointed.

How to output complete details

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

Calling superclass in main method

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);
}

My toString() is returning only one object times the number of the total object

Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?

Categories