Object creation across multiple files (Java) - java

so I have 2 files called Employee.java and Write.java (These two are within the same package). Say within Employee.java I have
public class Employee {
private String firstName = "test";
private String lastName = "ing";
public Employee(String first, String last) {
firstName = first;
lastName = last;
}
public Employee(Employee copy) {
firstName = copy.firstName;
lastName = copy.lastName;
}
}
Then within my Write.java I want to create an object of type Employee called temp. Like
public void obtainInfo(Employee temp) {
String firstName = temp.firstName;
String lastName = temp.lastName;
}
However I get an error that tells me that it cannot find the symbol in the line that is.
public void obtainInfo(Employee temp) {
I was just wondering where I went wrong that I can't create an object within different files. Despite them being in the same package I can't access them?
I want to be able to incorporate this later on to help me build a text file from reading an array list, but I figured to first start with reading a single line from an object.

It sounds to me that you are trying to set something up so that you can make a copy of an Employee and be able to write the properties to a text file. This won't write to a text file but I think it may clear some things up for you.
public class Employee {
private String firstName;
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(Employee copy) {
firstName = copy.firstName;
lastName = copy.lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Employee");
sb.append("{firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append('}');
return sb.toString();
}
}
TestClass.java
public class TestClass {
public static void main(String[] args){
//First we have to have one to copy
Employee emp = new Employee("Joe", "Dirt");
//Now we have a copy
Employee emp2 = new Employee(emp);
//Calls the Employee.toString() method and sends it to System.out
System.out.println("Employee 1 : " + emp);
System.out.println("Copy of Employee 1 : " + emp2);
}
}

Make sure that Write.java's class has the same level of access as Employee (IE: Public). If this is not the issue, I would show the code from Write.java specifically as that is most likely where the problem is coming from.

Related

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

Find multiple element with similar values in ArrayList?

i have a class called Student has two variables:
String lastName;
String firstName;
public Student(String lastName,String firstName){
this.lastName = lastName;
this.firstName = firstName;
}
public Student(String lastName){
this.lastName = lastName;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public boolean equals(Object obj) {
String getLastName = ((Student) obj).getLastName();
return lastName.equalsIgnoreCase(getLastName);
}
in the Main class i have created an ArrayList
private static ArrayList<Student> listOfStudents = new ArrayList<>();
and i have created this method to get the students from ArrayList
public void findStudent(String lastName){
for (int i=0;i<listOfStudents.size();i++){
if (listOfStudents.get(i).equals(new Student(lastName))){
System.out.println(listOfStudents.get(i));
}
}
}
I have overridden equals() to check by last name.
Now everything is well, but when i add duplicate last name like below:
listOfStudents.add(new Student("Tamoussat","Abdelillah"));
listOfStudents.add(new Student("Tamoussat","Fatima"));
listOfStudents.add(new Student("Soussi","Ahlam"));
I get only the first element, i want the way of how to get more than one element if they have the same last name?
Best Regards
public class Student {
private String lastName;
private String firstName;
public Student(String lastName, String firstName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
You can filter your list with the java stream api:
public static void findStudent(List<Student> listOfStudents, String lastName){
listOfStudents.stream().filter(s -> s.getLastName().equals(lastName)).forEach(student -> {
// for each student with the lastName
System.out.println(student);
});
}
The mistake will be in your equals() method, as running the code above works as expected with my own implementation of equals() which just compares lastName of this with the object argument.
But still, try to improve this method
public void
findStudent(String lastName)
{
for (Student student : listOfStudents)
{
if (student.lastName().equals(lastName))
{
System.out.println(student);
}
}
}
or any other version like #CodingSamples 's
Your equals() and hashCode() should work, despite they are not canonical. I would write it in a more better way:
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return Objects.equals(lastName, student.lastName);
}
#Override
public int hashCode() {
return Objects.hash(lastName);
}
But this does not explain why your code returns only one item from the array. You can try my implementation or post more precisely code you execute with data you use and the result of execution.
Thanks for helping, finally i found the problem was in my code, i have a method to add students to array, in that method i used
if(!listOfStudents.contains(new Student(lastName,firstName)){}
So the problem was in other method, when it found duplicate element it doesn't add it to the ArrayList, when i deleted this if statement from that method, code worked good, Best Regard

Set , Get Method in Java

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

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

How to debug a java code with getters and setters?

I was given an empty class and instructed to fill it with instance variables and methods with bodies, which set or get values from the instance variables. Then I am to open another java file where code creating a new Contact object was provided and instructed to add additional code that uses that object to test all the methods created in the Contact class.
I am using the program Eclipse for coding/testing. The only things are correct are my method headers. When testing with what I have written (below) I get a null, null response (that is when I remove what wrote about the setPhoneNumber. When it's included I get a worse looking error
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: phoneNumber cannot be resolved to a variable.)
Any assistance on getting the get/set methods to work will be much appreciated. I am entirely new to any programming and have looked at about dozens of examples and have tried many variations with no success.
public class Contact
{
//Instance Variables
private String firstName;
private String lastName;
private int phoneNumber;
public String getFirstName() //method to retrieve first name
{
return this.firstName;
}
public void setFirstName(String firstName) //method to set the first name
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public int getPhoneNumber()
{
return this.phoneNumber;
}
public void setPhoneNumber(int phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public void call()
{
System.out.printf(getFirstName(), getLastName(), getPhoneNumber());
}
}
Here is the other java file used to test the Contact class above:
public class ContactTestDriver
{
public static void main(String[] args)
{
Contact contact = new Contact();
//all above was given; below are my code additions
String myContact;
myContact = contact.getFirstName();
contact.setFirstName();
System.out.println(myContact);
myContact = contact.getLastName();
contact.setLastName();
System.out.println(myContact);
int myNumber;
myNumber = contact.getPhoneNumber();
contact.setPhoneNumber(phoneNumber);
System.out.println(myNumber);
}
}
After some helpful comments I have made changes but still no success. My error is "myContact cannot be resolved to a variable"
Here is the revised code:
public class Contact
{
//Instance Variables
private String firstName;
private String lastName;
private int phoneNumber;
public void setFirstName(String firstName) //method to set the first name
{
this.firstName = firstName;
}
public String getFirstName() //method to retrieve first name
{
return this.firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
public void setPhoneNumber(int phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public int getPhoneNumber()
{
return this.phoneNumber;
}
public void call()
{
System.out.printf("Who to call ", getFirstName(), getLastName(), getPhoneNumber());
}
}
And this is the code to test the Contact class:
public class ContactTestDriver
{
public static void main(String[] args)
{
Contact contact = new Contact();
//all above was given; below are my code additions
String firstName = "a"; //define first name
contact.setFirstName(firstName); //then set it
myContact = contact.getFirstName(); //then get it
System.out.println(myContact);
String lastName;
contact.setLastName(lastName);
myContact = contact.getLastName();
System.out.println(myContact);
int myNumber = 123;
contact.setPhoneNumber(phonNumber);
myNumber = contact.getPhoneNumer();
System.out.println(myNumber);
}
}
When you call contact.setFirstName(); which take String parameter you didn't pass the first name
public void setFirstName(String firstName){...}
and also with contact.setLastName(); : this also needs to send parameter
like this :
String lastName="//last name";
contact.setLastName(lastName);
and you need to know that we use the setter method before getter method
so first set the names then get it
String firstName = "a";////define the first name
contact.setFirstName(firstName); //// then set it
myContact = contact.getFirstName(); /// then get it
System.out.println(myContact);
String lastName = "b";
contact.setLastName(lastName);
myContact = contact.getLastName();
System.out.println(myContact);
int myNumber = 123;
contact.setPhoneNumber(myNumber);
myNumber = contact.getPhoneNumber();
System.out.println(myNumber);
This is what you have:
myContact = contact.getFirstName();
contact.setFirstName();
First you are getting, then you are setting. Reversing them makes more sense:
contact.setFirstName();
myContact = contact.getFirstName();
Moreover, set methods like setFirstName should receive a String parameter:
contact.setFirstName("Johny");
You can use Eclipse debugging tool.Run you java class in debug mode and add break points where ever you need to analyze data.
getter is just a method getting a field and setter is setting a new field.
you must set some values first i.e
int myNumber;
myNumber = contact.getPhoneNumber();
contact.setPhoneNumber(phoneNumber);
System.out.println(myNumber);
int myNumber= "983445556"; // here you are creating an instance
or you can do it by
contact.setPhoneNumber(32435435345);
similarly for rest cases
Here phoneNumber is not a defined variable in your main method
int myNumber;
myNumber = contact.getPhoneNumber();
contact.setPhoneNumber(phoneNumber);
it should be defined.

Categories