Is my Java enum class correctly formatted? - java

From a previous question I asked on enums, I was able to understand what enums really are, but I'm still very new to them in practicing. In my lab, it unexpectedly says:
"Create class Manager which extends class SalariedEmployee and contains the following information:
-The name of the department being managed by this employee. Create an enumerated class with
the 4-8 different departments such as Payroll, Production, Accounting, Research, Marketing, etc.
-Number of employees (an integer) – a value between 1 and 100. "
Would it seem to you guys if I'm doing this correctly? :
public enum Department {
Payroll(10), Production(25), Accounting(30), Research(25), Marketing(7);
//DepartmentName(numberOfEmployees)
private int numberOfEmployees;
private Department(int numberOfEmployees) {
this.numberOfEmployees = numberOfEmployees;
}
}
Do you guys think this is valid and sufficient? Obviously the professor knows for sure what he's asking of, but from your own interpretation, am I doing this correct?
Also, If my super constructor's validation range for an int is a bigger range than the one I want the specific parameter for my subclass to have, would just issuing an if/else statement after the super() call be sufficient? For example:
public SalariedEmployee(String name, String number, double salary, double deductions) {
super(name, number);
if (salary >= 40000.00 && salary <= 160000.00) {
this.yearlySalary = salary;
} else {
this.yearlySalary = 75000.00;
BUT in the subclass I want the range to be between 40k-100k, so I did this:
public Supervisor(String name, String number, double salary, double deductions, int goals) {
super(name, number, salary, deductions);
if (salary >= 40000.00 && salary <= 100000.00) {
this.yearlySalary = salary;
} else {
this.yearlySalary = 75000.00;
}
}
Is that sufficient enough to override the super constructor's argument range/specifications? Thank you.

I doubt that the teacher intends for you to put the number of employees into the enum. Additional info provided to enums is usually data that is not subject to change. The number of employees is something that changes frequently. I believe the requirement of your instructor says that the Manager class should include a property that states how many employees are managed by the Manager, something like this:
public class Manager extends SalariedEmployee {
private Department department;
private Integer numEmployees;
...
}
Since this appears to be an assignment, I don't want to give too much more code than this. Good luck!
I think what you are asking in the second part of your question is sufficient. After calling super() in your constructor, you are free to change the values of any of the properties set by the super() method to different values. I'm not sure I fully understand what you are trying to do with the salary ranges, but I think you have given enough information to say that what you are doing is sufficient.

All you really need to put in your subclass constructor is
super(name, number, salary,deductions);
if(salary>100000.00){
this.yearlySalary=75000.00;
}
because you are aleady checking if it is between 40000 and 160000 in your superclass. Your enum looks to be correct.

Related

First Object Oriented Assignment! Does this ensure that yearsWorked is not < 0?

This is my first Object Oriented Assignment. I am kind of lost. I am not sure if I did this instruction correctly.
"Do not allow the yearsWorked attribute to be set to values less than zero. If an attempt is made to set the yearsWorked attribute to less than zero, have your set method set yearsWorked to zero."
Here is my assignment
Part 1: of HW #9a - Employee class (class data type for Employee)
Write a class named Employee (you must name it this) that has the following attributes (fields):
name: The name attribute should be a String that holds an employee's first and last name
idNumber: The idNumber attribute is a String that holds an employee's ID number
department: The department attribute is a String that holds the name of the employee's department that they work in
position: The position attribute is a String that holds the name of the employee's job title
yearsWorked: The yearsWorked attribute holds the number of years the employee has worked at the company
Write Get and Set methods for each attribute: name, idNumber, department, position, and yearsWorked.
Do not allow the yearsWorked attribute to be set to values less than zero. If an attempt is made to set the yearsWorked attribute to less than zero, have your set method set yearsWorked to zero.
Here is my code
public class Homework9a
{
{
/*MEMBER FIELDS*/
String name= "";
String idNumber= "";
String department="";
String position= "";
double yearsWorked=0;
double years=0;
}
public String getName(String name)
{
return name;
}
public String getidNumber(String idNumber)
{
return idNumber;
}
public String getdepartment(String department)
{
return department;
}
public String getposition(String position)
{
return position;
}
public void yearsWorked (double yearsWorked, double years)
{
if(yearsWorked > 0)
{
yearsWorked = years;
}
else
{
yearsWorked = 0;
} }
}
Clear Instruction : 'Write a class named Employee (you must name it this)....'
Yet you decided to name it Homework9a
there is not a single instruction that talks about an attribute called years yet you decided to add it.
Instruction clearly says "Write Get and Set methods for each attribute: name, idNumber, department, position, and yearsWorked" yet you decided to only write one Setter (which itself is incorrect)
This content will help you a lot. Practice, Practice and Practice.
I assume you're asking about
If an attempt is made to set the yearsWorked attribute to less than zero, have your set method set yearsWorked to zero.
If that's the case, then this test
if(yearsWorked > 0)
{
yearsWorked = years;
}
else
{
yearsWorked = 0;
}
is almost correct. However, there are a few other issues here.
First, I'd suggest sticking with the standard naming conventions for your methods.
public void yearsWorked (double yearsWorked, double years)
This should be setYearsWorked. Also (and this is important), you should remove the double yearsWorked parameter - you shouldn't need it and its presence makes it unclear whether you're trying to set the parameter or the field in the method body. (In this case, it'll set the parameter, which isn't what you want).
You also want to change this line:
if(yearsWorked > 0)
To
if (years > 0)
Also, there shouldn't be {} around the fields.
Finally, while Java syntax doesn't technically require it, make sure you always explicitly set access modifiers for your fields.

How to create a class that calls upon methods from a different class?

I recently started learning java this year in my school. We've gotten to a short chapter where we are creating a class that calls multiple methods from inside the class or outside the class. Our teacher gave us a demo showing us an class using methods from another class. This is the code from his example of this and called the class Dog. He then creates another class called DogDriver. We then received a coding project. Here's what is must include. It's a program for a bank that must allow the owner to enter the bank account owner's name, money balance, and the amount the depositor would like withdrawn from their account. It will also need to allow the depositor to deposit and withdraw funds, and give error when the withdrawal exceeds the accounts balance. It needs 2 or more methods to call the program
I referenced back to the example he gave me and am having a hard time understanding the example so I can make the program. I think I get what it does, but when ever I try and code it myself, I seem to always get the “invalid method declaration; return type required”. I know I am doing something wrong but I would like to understand the way the program code I linked above works and how it can be used.
Any help is appreciated, Thank You
Here's my code. I was trying to understand the example program he created so I had taken it and edited it.
//January 27, 2015
public class Testing1{
private double Balance;
private String Name, Middle, Last;
public AccountBalance(){
Name = "Phillip";
Middle = "J.";
Last = "Fry";
Blance = 300;
}
public accountBalance(String FirstName, String MiddleName, String LastName, double InitialBal){
Name = FirstName;
Middle = MiddleName;
Last = LastName;
Balance = InitialBal;
}
public String Name(){
return Name;
}
public void SetBalance(double InitialBal){
Balance = InitialBal;
}
public double GetBalance(){
return Balance;
}
}
public AccountBalance(){...}
//and
public accountBalance(String FirstName, String MiddleName, String LastName, double InitialBal){...}
are (I assume you want them to be) constructors, therefore, they need to be the same name as the class name (here it is Testing1), and they are CASE SENSITIVE meaning AccountBalance does not equal accountbalance, eith change your constructors to match the class name :
public Testing(){...}
or refractor your class name to be AccountBalance
The error is because java thinks they are methods, which need return types.
Oh and, Balance = 300 is spelt wrong in your first constructor
First of all, if you would like to call a method from a different class, it must be public class. Then you can call those methods from your main method.
Dog myDog = new Dog();
myDog.colour("White");
Java Method Calling

Java: Adding Fields to Sub-Class Constructors?

For example, say I have the 3 classes Person, Student and Teacher. The Person class would have general details about the people (name, age, email etc) which both the Student and Teacher class will extend. On top of this though, these classes will also have their own unique fields (e.g. wage & courseTaught (or "tought"?) for Teacher and schoolYear & classNumber for Student). If I just show the initial code I've got, maybe someone could point me in the right direction. Because Person doesn't have a courseTaught field, currently I'm just getting the output "Josh (null)" rather than "Josh (Computer Science)". Any help would be appreciated :)
public class Main {
public static void main(String args[]){
Teacher t = new Teacher("Josh", "Computer Science");
System.out.println(t.name + " (" + t.courseTaught + ")");
}
}
public class Person {
String name;
public Person(String pName){
name = pName;
}
}
public class Teacher extends Person{
String courseTaught;
public Teacher(String tName, String tCourseTaught){
super(tName);
}
}
The problem is simpler than you think. You're on the right track but you forgot to assign courseTaught in your Teacher constructor. The initial value of courseTaught is null and it stays that way because you never assign it to anything.
You'd want something like this:
public Teacher(String tName, String tCourseTaught){
super(tName); // <- takes care of Persons's field
courseTaught = tCourseTaught; // <- but don't forget to set the new field, too.
}
And yes, "taught" is the correct word.
As an aside, since you did tag your question "oop", you may want to check out this article on encapsulation for some information about the use of "getters" and "setters".

How to inject property values into enum?

I'm using Spring to resolve property values from properties file, usually with #Value("${my.property}").
Now I have an enum that should have an application-wide configurable static number. For example:
public enum PersonType {
ADULT, CHILD;
private static final int MAX_CHILD = 17;
public static PersonType fromAge(int age) {
return age <= MAX_CHILD ? CHILD : ADULT;
}
}
How could I make the max child age configurable and injectable by Spring?
It's an interesting question, how one handles variables that is the same for all objects of the class and does not change during runtime, and at the same time is allowed to be configurable between executions. Since the first two prerequisites dictate that the variable should be static and final (e.g. a constant), the third really doesn't fit in, meaning that there will be no pretty way to achieve all three (reflection is needed, or one has to drop either the static or the final constraint).
Since there is no pretty solution to the way things are modeled now, I think the wisest would be to take a step back and rethink the placement of the variable: Is it necessary to keep this logic in the enum itself? What is different when changing the value of the constant, the enum itself, or something else? In what cases does this constant have to change it's value?
In your example it might be that different countries have different thresholds for what is regarded as adult, or that the threshold changes, then maybe a small service that determines which PersonType a Person has is the right way to go.
#Service
public class PersonTypeService {
#Value("${threshold.for.adulthood}")
private int thresholdForAdulthood;
public PersonType determinePersonType(final Person person) {
if (person.getAge() >= thresholdForAdulthood) {
return PersonType.ADULT;
}
return PersonType.CHILD;
}
}
In general I like to let enums only answer the "what", and leave the "how" and the "why" to domain classes and services. In the example, all the enum needs to know is the values it provides a person, why it should provide a certain value, or how it is determined, does not belong in the enum.
Moving the logic to get proper enum based on configurable age can be one of the solution
class PersonTypeFinder
{
private int maxChildAge; // set this from spring
....
public PersonType getPersonType(int age)
{
return age <= maxChildAge ? PersonType.CHILD : PersonType.ADULT;
}
}
enum PersonType
{
ADULT, CHILD;
}

Design of a scholar system

I'm creating a web-based scholar system for students to look up their scores, view their schedule, etc. However, I'm having a problem on architecting this system, as in I can't find a suitable way to associate the data.
There's a student, which is in a (school) class. The student has a scoreboard. The (school) class has a list of the "assignments" the students had for each subject, but it only has informations such as name, maximum score, weight. The actual score sits on the student's scoreboard.
Many students are in the same class.
Only one instance of an assignment should exist at any time, and it should live in the SchoolClass object, because it's then applied to the whole class instead of per-student.
A student, then, should only hold it's own score, and reference the rest of the assignment data from outside.
How do i reference the specific homework from the student?
That was kind of confusing. This is what I currently have:
class Student extends Person {
private SchoolClass schoolClass;
private Scorecard scorecard;
}
class Subject {
private String name; /// "Compilers II", "Data Structures", etc.
}
class SchoolClass {
private Course course; // "Computer Science", "Administration", etc.
private List<Assignment> assignments;
class Assignment {
private Subject subject;
private int maxScore;
private int weight;
private String name; // "Test about material resistance II"
}
}
class Scorecard {
// How to reference each assignment from each subject in this student's class cleanly?
}
Is my design going on a good direction or should I just erase this and begin again? Thanks!
This is looking pretty good, but there are a couple things I would like to point out.
Is the Person classs abstract? If so then well done! If not it probably should be because person is a general term. For more information about when to make a class abstract check out my answer to this question.
Well done using Assignment as a nested class! It directly relates to SchoolClass so it should be nested, but how about the Subject class? That seems to be directly connected to SchoolClass as well therefore it would not be a bad idea to make Subject a nested class also.
As for referencing a single homework assignment, this depends on how you want to get it by. If you want to get it by index then use a getter. To do this you could simply put this code in SchoolClass:
public Assignment getAssignment(int index)
{
return assignments.get(index);
}
However if you want to use reference it by name instead it is a little more tricky, but still pretty strait-forward. You would add a getter to your Assignment class like this:
public String getName()
{
return name;
}
Then you would simply have to write another getter for SchoolClass like this:
public Assignment getAssignmentByName(String name)
{
for (Assignment assignment : assignments)
{
if (assignment.getName().equals(name))
return assignment;
}
System.out.println("No assignment found by the name of " + name);
return null;
}
Hope that helps! If you have any questions don't hesitate to ask!
Edit:
In order to let your assignment objects describe themselves they should override Object.toString(). The following code should be put in your assignment class.
// I noticed that you only have a maxScore variable, I think that a score variable is needed
private int score;
#Override
public String toString()
{
return "The score for this assignment is: " + score;
}

Categories

Resources