Calling a private method within another class into a class - java

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.

Related

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

How do I acces the methods within the extended class?

I have the following:
main.java
public class main {
public static void main(String[] args){
Player startingPitcher = new Player("Doug", "Mellon",
"Pitcher", 29);
startingPitcher.setThrowingArm("right");
}
}
Player.java
class Player
{
private String firstName, lastName, position;
private int age;
public Player(String firstName, String lastName, String position, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
this.age = age;
}
private String getFirstName(){
return this.firstName;
}
private void setFirstName(String newFirstName){
this.firstName = newFirstName;
}
private String getLastName(){
return this.lastName;
}
private void setLastName(String newLastName){
this.lastName = newLastName;
}
private String getPosition(){
return this.position;
}
private void setPosition(String newPosition){
this.position = newPosition;
}
private int getAge(){
return this.age;
}
private void setAge(int newAge){
this.age = newAge;
}
}
Pitcher.java
public class Pitcher extends Player{
public String throwingArm;
public int fastballMPH;
public Pitcher(String firstName, String lastName, String position, int age,
String throwingArm, int fastballMPH) {
super(firstName, lastName, position, age);
this.throwingArm = throwingArm;
this.fastballMPH = fastballMPH;
}
public String getThrowingArm(){
return this.throwingArm;
}
public void setThrowingArm(String newThrowingArm){
this.throwingArm = newThrowingArm;
}
private int getFastballMPH(){
return this.fastballMPH;
}
private void setFastballMPH(int newFastballMPH){
this.fastballMPH = newFastballMPH;
}
}
My main is throwing the following error:
Error:(6, 24) java: cannot find symbol symbol: method
setThrowingArm(java.lang.String) location: variable startingPitcher
of type Player
I understand the error - I think - but I thought you could access the methods if you were using inheritance.
How can I set the throwing arm for the Player object in my main?
Sorry if this question is worded poorly. If there is anything I can add to clarify my question, please don't hesitate to ask.
Thank you all very much for your time.
Variable startingPitcher in method main(), of class main, is an instance of Player and not an instance of Pitcher, hence it has no setThrowingArm() method.
You need to create an instance of Pitcher, i.e.
Pitcher startingPitcher = new Pitcher("Doug", "Mellon", "pitcher", 29, "right", 90);
Note that this is what the error message is telling you, namely that variable startingPitcher is an instance of Player (and not an instance of Pitcher).

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

Output List Is Wrong?

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

Constructors from extended class in 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.

Categories