Java Subclasses last instance overwriting values - java

I'm a web developer dabbling in Java (again) and I'm having trouble with something.
Basically, I have a superclass Employee with two subclasses that extend it called Management and Programmer. The Employee class contains an array employees that is basically an array of Employee objects.
Here's the important snippets of two of the classes (Employee and Management) and the final main method. I'll explain the output at the bottom.
public class **Employee** {
private static String firstName;
protected static int MAXEMPLOYEES = 5;
protected Employee[] employees = new Employee[MAXEMPLOYEES];
protected int totEmployees = 0;
public Employee(String first) {
setFirstName(first);
}
public void setFirstName(String str){
firstName = str;
}
public String getFirstName(){
return firstName;
}
public boolean addEmployee(String fname) {
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
Employee empl = new Employee(fname);
employees[totEmployees] = empl;
added = true;
totEmployees++;
}
return added;
}
}
public class **Management** extends **Employee** {
private String title = "Project Manager";
public Management(String fname, String t){
super(fname);
title = t;
}
public boolean addManagement(String fname, String t){
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
employees[totEmployees] = new Management(fname, t);
added = true;
totEmployees++;
}
return added;
}
}
-------------------------------------
package employee;
public class EmployeeApplication {
public static void main(String[] args) {
Employee[] empl = new Employee[3];
empl[0] = new Employee("Kyle");
empl[1] = new Management("Sheree", "Director");
System.out.println(empl[0].getFirstName());
}
}
Now, I expect the system to print out "Kyle", but it prints out "Sheree". Any ideas???

private static String firstName;
You made firstName static, which means all instances share the same name. You'll need to remove the static modifier in order for different Employees to have different names. You'll also need to change the private access modifier to protected in order for the field to be inherited by subclasses.

private String firstName;
remove static;
Kyle was overridden by Sheree, that is why you are getting that output

Related

How to use BiConsumer to accept an object having an object, list of strings, and variables?

I am trying to use BiConsumer to accept an object that contains variables, an object and a list of strings in Java. I am not sure how to set the values into one object if using just BiConsumer. Maybe, if I tried to wrap Student object in a List and pass it into a new Student might help, but so far I get a null object. I haven't seen a lot of post with object containing just variables in one object and using BiConsumer.
#Test
public void testStudent() {
List<Object> objectList1 = new ArrayList<>();
Student student = new Student();
StudentLevel studentLevel = new StudentLevel("freshman", true);
List<String> studentLists = Arrays.asList("Maria", "Jose", "Juan");
Student student1 = new Student("Maria", "Lopez", "A", studentLevel, studentLists);
objectList1.add(student1);
BiConsumer<Object, List<Object>> biconsumer = (obj, list) -> {
for (Object object: list) {
// set and get but how?
// obj = object;
}
};
// To accept values from the object list see below for desired output
biconsumer.accept(student, objectList1);
// For debugging purpose
System.out.println("All Student: " + student);
}
public class Student {
private String name;
private String lastName;
private String grade;
private StudentLevel studentGrade;
private List<String> studentList;
public Student(final String name, final String lastName, final String grade, final StudentLevel studentGrade, final List<String> studentList) {
this.name = name;
this.lastName = lastName;
this.grade = grade;
this.studentGrade = studentGrade;
this.studentList = studentList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public StudentLevel getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(StudentLevel studentGrade) {
this.studentGrade = studentGrade;
}
public List<String> getStudentList() {
return studentList;
}
public void setStudentList(List<String> studentList) {
this.studentList = studentList;
}
}
public class StudentLevel {
private String level;
private Boolean pass;
public StudentLevel(final String level, final Boolean pass){
this.level = level;
this.pass = pass;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public Boolean getPass() {
return pass;
}
public void setPass(Boolean pass) {
this.pass = pass;
}
}
Desired output:
student = {Student#887}
name = "Maria"
lastName = "Lopez"
grade = "A"
studentGrade = {StudentLevel#889}
level = "freshman"
pass = {Boolean#906} true
studentList = {Arrays$ArrayList#890} size = 3
0 = "Maria"
1 = "Jose"
2 = "Juan"
You are assigning local reference of object to obj (won't copy the values)
obj = object; // means, student = object
no change will be reflected outside the scope of the consumer, instead, you need to modify the state using setters as:
((Student) obj).setName(((Student) object).getName());
obj = object; // after this point, student object won't be accessible in the current scope.
Note: You should have getters and setters to access private properties outside Student class, and this example just demonstrates the working by assigning name property.
Reference:
• Classes and Object

return a subclass-type in java

I have a subclass "OnlineCourse". It´s a subclass of "Course". I want to return "OnlineCourse" in my class "Student". But instead of "EIST" I get back null.
Here´s what I have:
public class Student {
public String matriculationNumber;
public String name;
public int age;
public Course study() {
TODO 4: Comment the code below back in
Change the Course type to OnlineCourse and set its
title to "EIST"
return the new course
// Course course = new Course();
// course.join();
// return course;
Course EIST = new OnlineCourse();
EIST.join();
return EIST;
}
}
Subclass that extends course and should be initiated as the return type for "EIST" in the class Student.
public class OnlineCourse extends Course{
public URL livestreamUrl;
public Course join() {
System.out.println("joined the course " + title);
return this;
}
public Course drop() {
System.out.println("dropped out of the course" + title);
return this;
}
}
public abstract class Course {
public String title;
public String description;
public LocalDate examDate;
public List<Lecture> lectures;
public abstract Course join();
public abstract Course drop();
}
Main- Method:
public class Main {
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study();
}
}
I think you're saying the course title is showing as null. In which case you have to set it for it to print. I'd also note that where you have EIST - that's just a variable name, it can be anything and doesn't have any affect on any values.
If I were to guess, I think you'd want something like this -
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study("EIST");
}
And in Course, you'd want a setter method for the title like, -
public setCourseTitle(String title) {
this.title = title;
}
And in Student
public Course study(String courseTitle) {
Course EISTCourse = new OnlineCourse();
EISTCourse.setCourseTitle(courseTitle);
EISTCourse.join();
return EISTCourse;
}

If I create an array of the parental class, how do I access a method from the sub class through the array object?

I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();

Generic linked list inside of linked list?

I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}

I don't understand private variables?

There is nothing wrong with the code, but I don't understand why you have to create a private String name, and then equals that string with the string from method i.e. name = n.
public class Person {
private String name;
public Person (String n) {
name = n;
}
public String getName() {
return name;
}
public boolean sameName(Person other) {
return getName().equals(getName());
}
}
A private variable can't be accessed from outside the class, but only by the methods inside the class so it's safer

Categories