I am supposed to refactor duplicated attributes in Student class. I have Student and Professor classes as below. I am really confused about how to do refactoring with attributes. Should I add a new class, or made modifications in one of the classes. If so, how? I could not understand how to proceed with this to-do.
private final String matrNr;
private final String name;
private final int age;
private int semester;
private final String email;
public Student(String name, int age, String email, String matrNr, int semester) {
this.matrNr = matrNr;
this.name = name;
this.age = age;
this.semester = semester;
this.email = email;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getSemester() {
return semester;
}
public String getMatrNr() {
return matrNr;
}
public void increaseSemester(){
semester = semester + 1;
}
}
And the professor is a like:
private final String persNr;
private final String name;
private final int age;
private final String email;
public Professor(String name, int age, String email, String persNr) {
this.persNr = persNr;
this.name = name;
this.age = age;
this.email = email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPersNr() {
return persNr;
}
}
Thanks for any kind of helps!
Your goal is to refactor duplicated attributes in the Student and Professor classes. The way to do this is to create a parent class which defines the common attributes (like "name"), and modify Student and Professor classes to extend the common parent class. In this way, both Students and Professors can have a "name", even though you have defined "name" only once in the common parent.
Below shows how you could do this with a common "Human" parent class, how the constructors would work, and how you could define a Student-only attribute (semester).
Here is a simple version a common Human class:
common "Human" class
each Human has a "name"
the name is set in the constructor (so when you're creating an object) and cannot be changed later ("name" is final; also no "setHuman()")
class Human {
private final String name;
public Human(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Here's a simple Professor class:
by definition, a Professor is a Human (Professor extends Human)
when creating a Professor, you must specify the "name" (which is then passed to the Human constructor)
once you have a Professor, you can call getName() (which is defined on the Human class)
class Professor extends Human {
public Professor(String name) {
super(name);
}
}
Here's a simple Student class:
Student is a little different - in addition to a name, it also has a "semester"
when creating a Student, the constructor requires a name and semester, and the Student class itself keeps track of "semester" – so it's fine to have semester defined on Student, and name defined on Human.
you can call getName() (defined on Human)
you can call getSemester() (defined on Student)
class Student extends Human {
private final int semester;
public Student(String name, int semester) {
super(name);
this.semester = semester;
}
public int getSemester() {
return semester;
}
}
If I use the super() method, which I know it needs to be the first line in the child's constructor, would I have to use it for every following constructor? Also, when using the super() method, does that inherit every field from the parent class automatically or do I still need to initialize those fields in the child constructors? Let's say that I don't use the super() method, to inherit from the parent class, would I need to initialize the fields used in the parent class in the child class? Kind of a loaded question, this my first time asking on here. I am a student almost finished with my 2nd year so I am trying to get a good grasp on as much as I can. Any feedback would be greatly appreciated. Thank you. I have an example of what I'm doing below.
package Employee;
public class Employee {
// declare employee class fields
private String empName;
private String empId;
private String hireDate;
// default constructor
public Employee()
{
empName = "";
empId = "";
hireDate = "";
}
// constructor with arguments passed in
public Employee(String name, String id, String date)
{
empName = name;
empId = id;
hireDate = date;
}
// set methods for employee class
public void setEmpName(String name)
{
empName = name;
}
public void setEmpID(String id)
{
empId = id;
}
public void setHireDate(String date)
{
hireDate = date;
}
// get methods for employee class
public String getName()
{
return empName;
}
public String getID()
{
return empId;
}
public String getDate()
{
return hireDate;
}
// create production worker class; child to employee class
public class ProductionWorker extends Employee
{
private int shift;
private double payRate;
// default constructor
public ProductionWorker()
{
super();
shift = 0;
payRate = 0.00;
}
// constructor with args passed in
public ProductionWorker(int s, double p)
{
super();
shift = s;
payRate = p;
}
}
I have the following parent class:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
And 2 child class which extends parent:
public class FullTimeEmployee extends Employee {
private double salary;
public FullTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
}
public double getSalary() {
return salary*2;
}
}
public class PartTimeEmployee extends Employee {
private double salary;
public PartTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
}
public double getSalary() {
return salary;
}
}
The scenario:
I am using an ArrayList to contain information about employees. The ArrayList is created at the start of the program, and the type of employee being added into the Arraylist is a child extending parent and only known at runtime through user's input
public class EmployeeApplication {
public static void displayInfo(Employee employee) {
// How do I access the method getSalary() that belong to the specific type determined on runtime?
System.out.println(employee.getSalary()); // <--- ???
}
public static void main(String[] args) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Type of employee to add into arraylist: ");
String userInput = keyboardInput.nextLine();
// ArrayList to contain information about employees
ArrayList<Employee> employeeAL = new ArrayList<Employee>();
// Type of employee being created and added into ArrayList is dynamic and only known at run time based on user input
if(userInput.equals("full")) {
employeeAL.add(new FullTimeEmployee("John", 1000));
}
else {
employeeAL.add(new PartTimeEmployee("John", 500));
}
displayInfo(employeeAL.get(0));
keyboardInput.close();
}
}
Now the question:
how do I access the method getSalary() belonging to the specific child type that was determined on runtime? Since the object retrieved from the ArrayList is a parent type. Please note that the salary attribute only belongs to the child class.
My current implementation has me checking for the child type, typecasting it into that child type, and finally accessing the method belonging to the child.
I am trying to avoid typecasting because I believe I am doing things wrongly with regards to good Java coding practise. I'm missing something here but I just don't know what
Another method which I have thought about is to implement the method getSalary() in the parent class and overriding it in the child class, this way, I don't have to typecast but I don't know if this is the right practice since the salary attribute has got no relation with Employee at all:
// Parent
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
// ADDED THIS <----
public double getSalary() {
return 0.0;
}
}
// Child
public class FullTimeEmployee extends Employee {
private double salary;
public FullTimeEmployee(String name, double salary) {
super(name);
this.salary = salary;
}
// ADDED THIS <----
#Override
public double getSalary() {
return salary*2;
}
}
what am I doing wrongly and what is the best Java coding practice?
You can implement Employee as abstract and add getSalary() as an abstract method which forces subclasses of Employee to implement that method
public abstract class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
abstract protected double getSalary();
}
This is the Image that I'm going to transfer from UML to Java, I don't know how to lock them together and i don't know how to make one bankAccount locked to only one person.
How do i connect the 2 classes??
Here is my code so far
My main method
public class Upp5 {
public static void main(String[] args) {
Person2 david = new Person2();
BankAccount acc1 = new BankAccount();
BankAccount acc2 = new BankAccount();
david.setName("David");
david.setPnr("551012-8978");
acc1.setBnr("37");
acc2.setBnr("38");
System.out.println("Namn: " + david.getName() + " \nPersonnummer:" + david.getPnr());
System.out.println(acc1.getBnr() + "\n" + acc2.getBnr());
}
}
BankAccount.java:
public class BankAccount {
private String bnr;
private double balance;
public void credit() {
}
public void withdraw(){
}
public String getBnr(){
return bnr;
}
public void setBnr(String newAccount){
bnr = newAccount;
}
public void createAccount(String newNbr){
bnr = newNbr;
}
}
and Person2.java
public class Person2 {
private String pnr;
private String name;
//Koppla konto till pnr
public void addAccount(BankAccount a){
}
//Skapa Pnr och Namn
public void setPnr(String newPnr) {
pnr = newPnr;
}
public void setName(String newName){
name = newName;
}
// Hämta Pnr och Namn
public String getPnr(){
return pnr;
}
public String getName(){
return name;
}
}
You need to define a List<BankAccount> to your Person2 entity:
public class Person2 {
private String pnr;
private String name;
// list of bank accounts (from 0 to n) the Person can have.
private List<BankAccount> accounts;
//Koppla konto till pnr
public void addAccount(BankAccount a){
if (accounts = null) accounts = new ArrayList<BankAccount>();
accounts.add(a);
}
//Skapa Pnr och Namn
public void setPnr(String newPnr) {
pnr = newPnr;
}
public void setName(String newName){
name = newName;
}
// Hämta Pnr och Namn
public String getPnr(){
return pnr;
}
public String getName(){
return name;
}
// include getters setters
}
EDIT1: as suggested by #NathanCastlehow if you want double relationship, BankAccount.java must have a Person2 attibute
public class BankAccount {
private String bnr;
private double balance;
// one bank account can only be owned by a single Person
private Person2 person;
public void credit() {
}
public void withdraw(){
}
public String getBnr(){
return bnr;
}
public void setBnr(String newAccount){
bnr = newAccount;
}
// generate getters setters
public Person2 getPerson(){
......
}
}
You didn't put any arrows in your diagram, so we don't know if the bankaccount knows the person it is linked to. The most logical thing to do is; let the Person have a List which you always initiate in the Person's constructor.
If you want the bankaccount to know the person that owns him (which seems logical to me), let the Bankaccount have the property "Person owner" and let the constructor be require a Person to exist. I don't understand why you have made a Person2 instead of a Person class.
Tips for you: Never (!!!) use parameters like; 'a' or properties like 'nBr' because other people wanna see in an instance what they are instead of guessing. :-) And try to make some security rules (that's why I put booleans in the classes).
Solution:
Person:
public class Person {
List<BankAccount> bankAccounts;
private String name;
private String pNbr;
public Person(String name, String pNbr) {
this.name = name;
this.pNbr = pNbr;
}
public void addAccount(BankAccount newAccount){
bankAccounts.Add(newAccount);
}
}
Bankaccount:
public class BankAccount {
private String nBr; //maybe make this final?
private double balance;
private Person owner;
public BankAccount(String nbr, Person owner) {
this(nbr, 0, owner); // If you also want to support new empty accounts
}
public BankAccount(String nbr, double balance, Person owner) {
this.name = name;
this.pNbr = pNbr;
this.owner = owner;
}
public boolean Credit(double amount)
{ // TODO: write code
boolean result = false;
return result;
}
public boolean Withdraw(double amount)
{ // TODO: write code
boolean result = false;
return result;
}
}
So generally when this is done in models such as a relational model you would have an association class. So a class that has like an ID from a bank account and an ID of the person. You can lock variables using the final keyword in front of them which forces them to only be initialized once.
The easiest way to "link" classes in java is to add one of said classes as an attribute. For example:
// Make it private to maintain encapsulation
private BankAccount myBankAccount;
But this only works if you have a 1..1 (One to one) relationship.
Your UML diagram indicates a 1..n (One to many) relationship between Person and BankAccount classes. In other words,
A Person may have multiple BankAccounts.
This means you'll a have to use a structure to "keep" multiple BankAccounts in a single Person. Java already provides you with some handy classes:
ArrayList: Easy, quick, insertion-ordered list. Allows as many itens as you need.
Hashmap: Hash implementation of the Map interface. Provides a way to find itens using a "key" (Ex: An account's number). Very efficient.
A suggest reading some of those classes documentation. And you can always look for some neat examples on the internet ;)
I'm just working through a few things as practice for an exam I have coming up, but one thing I cannot get my head round, is using a variable that belongs to one class, in a different class.
I have a Course class and a Student class. Class course stores all the different courses and what I simply want to be able to do is use the name of the course, in class Student.
Here is my Course class:
public class Course extends Student
{
// instance variables - replace the example below with your own
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
And here is Student:
public class Student
{
// instance variables - replace the example below with your own
private int studentNumber;
private String studentName;
private int studentPhone;
private String studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = courseTitle;
}
}
Am I correct in using 'extends' within Course? Or is this unnecessary?
In my constructor for Student, I am trying to assign 'courseTitle' from class Course, to the variable 'studentCourse'. But I simply cannot figure how to do this!
Thank you in advance for your help, I look forward to hearing from you!
Thanks!
Am I correct in using 'extends' within Course? Or is this unnecessary?
Unfortunately not, if you want to know whether your inheritance is correct or not, replace extends with is-a. A course is a student? The answer is no. Which means your Course should not extend Student
A student can attend a Course, hence the Student class can have a member variable of type Course. You can define a list of courses if your model specifies that (a student can attend several courses).
Here is a sample code:
public class Student{
//....
private Course course;
//...
public void attendCourse(Course course){
this.course = course;
}
public Course getCourse(){
return course;
}
}
Now, you can have the following:
Student bob = new Student(...);
Course course = new Course(...);
bob.attendCourse(course);
I assume a Course is not a Student, so inheritance between those classes is probably a bad idea.
You have to declare them public.
A better way is the keep them private, and code a public getter for that variable. for example:
public Award getCourseAward(){
return this.courseAward;
}
Course should not extend Student. If you want to access the courseTitle field of Course, you need to pass a reference to a Course object to the Student and then do course.CourseTitle.
You cannot access private attributes of a class from another, this is one of the main principles of OOP: encapsulation. You have to provide access method to those attribute, you want to publish outside the class. The common approach is setter/getters - getters only, if you want to have your class immutable. Look here: http://en.wikipedia.org/wiki/Mutator_method#Java_example
It does not make sense to arbitrarily extend classes. Student is not a Course or vice versa, so you cannot extend them like that.
What you need to do is:
create a Course first:
Course aCourse = new Course(..);
create a Student:
Student aStudent = new Student(..);
assign the Course to the Student:
aStudent.setCourse(aCourse.title);
Extending Student with Couse because they are not of the same kind. Extending one class with another happens when specializing a more general (in a sense) one.
The solution would be to pass courseTitle as an argument of the Student constructor
There should be 3 separate objects here, a Course, a Student, and an Enrollment. An enrollment connects a Student to a Course, a Course has many Students, and a Student can enroll in many courses. None of them should extend each other.
First,
You are extending Student class in Course class, which means, student class gets all the coruse class properties. So, the student class does not have the courseTitle property.
Second, yes, it is unnesessary - you need to do the following:
public class Course
{
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
public class Student
{
private int studentNumber;
private String studentName;
private int studentPhone;
// This is where you keep the course object associated to student
public Course studentCourse;
public Student(int number, String name, int phone, Course course)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = course;
}
}
Example usage would be something like this:
Course course = new Course("ASD", "TITLE", null, "ME", 50, true);
Student student = new Student(1, "JOHN", "5551234", course);
And then, get the course information you need from student via, i.e.:
student.studentCourse.courseTitle;
Since now student.studentCourse will be a course object with all of its properties.
Cheers,
Maybe you do not need to add the course name to student. What I would do is add Students to some datastructure in Course. This is cleaner and reduces the coupling between Course and Student. This would also allow you to have Students being in more than one course. For example:
public class Course extends Student{
private Award courseAward;
private String courseCode;
public String courseTitle;
private Student courseLeader;//change to a student Object
private int courseDuration;
private boolean courseSandwich;
private Set<Student> students;//have course hold a collection of students
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, Student leader, int duration, boolean sandwich){
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
this.students=new HashSet<Student>();
}
public boolean addStudent(Student student){
return students.add(student);
}
public Set<Student> getStudents(){
return students;
}
}
As mentioned, stay away from the "extends" for this. In general, you shouldn't use it unless the "is-a" relationship makes sense.
You should probably provide getters for the methods on the Course class:
public class Course {
...
public String getTitle() {
return title;
}
}
And then if the Student class needs that, it would somehow get a hold of the course (which is up to you in your design), and call the getter:
public class Student {
private Set<Course> courses = new HashSet<Course>();
public void attendCourse(Course course) {
courses.add(course);
}
public void printCourses(PrintStream stream) {
for (Course course : courses) {
stream.println(course.getTitle());
}
}
}
Here below find out the solution of your problem and if you want to check below code on your machine then create a file named Test.java and paste the below codes:
package com;
class Course
{
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseAward = award;
courseCode = code;
courseTitle = title;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
public Award getCourseAward() {
return courseAward;
}
public void setCourseAward(Award courseAward) {
this.courseAward = courseAward;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getCourseTitle() {
return courseTitle;
}
public void setCourseTitle(String courseTitle) {
this.courseTitle = courseTitle;
}
public String getCourseLeader() {
return courseLeader;
}
public void setCourseLeader(String courseLeader) {
this.courseLeader = courseLeader;
}
public int getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(int courseDuration) {
this.courseDuration = courseDuration;
}
public boolean isCourseSandwich() {
return courseSandwich;
}
public void setCourseSandwich(boolean courseSandwich) {
this.courseSandwich = courseSandwich;
}
}
class Student
{
private int studentNumber;
private String studentName;
private int studentPhone;
private Course studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone, Course course)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = course;
}
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentPhone() {
return studentPhone;
}
public void setStudentPhone(int studentPhone) {
this.studentPhone = studentPhone;
}
public Course getStudentCourse() {
return studentCourse;
}
public void setStudentCourse(Course studentCourse) {
this.studentCourse = studentCourse;
}
}
class Award{
private long awardId;
private String awardName;
Award(long awardId, String awardName){
this.awardId = awardId;
this.awardName = awardName;
}
public long getAwardId() {
return awardId;
}
public void setAwardId(long awardId) {
this.awardId = awardId;
}
public String getAwardName() {
return awardName;
}
public void setAwardName(String awardName) {
this.awardName = awardName;
}
}
public class Test{
public static void main(String ar[]){
// use your all classes here
}
}