Setter without parameter Java OOP - java

I wanted to create an employeeID automatically whenever I create a new employee object. I am implementing OOP concept for my assignment. My problem is I wanted to use getter and setter to create for the id. However, since the id should be generated automatically so I can't put any value for the parameter when creating instance. How can I solve this?
private String employeeID;
public void setEmployeeID(String employeeID){
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
public String getEmployeeID(){
return employeeID;
}

To keep it simple:
You need or want to use public void setEmployeeId(String id) and its a basic requirement.
But if so, the idea of having such a method means that the class Employee should have any logic of id generation, instead by declaring such a method you say to the programmer that will use the Employee class: "Look, this class doesn't have an id, but you can create it and set".
If these are your intentions, then extract the logic of the id generation outside the employee class and use the "pure" setter:
main:
String id = generateId(...) // in this method there will be all the code with Random
Employee emp = new Employee();
emp.setId(id);
.....
class Employee {
private String id;
public void setId(String id) {this.id = id;}
}
Otherwise, if you do think that the Employee should generate an id by its own, you don't need a setter. In this case you can either call the generation code in constructor (not really recommended, but will work) or create an "init" method that will set the initial state of id to the employee object. In this case, whoever creates an Employee, will have to call this method:
public class Employee {
private String employeeId;
public class Employee(...) {...}
public void init() {
setupId();
}
private void generateEmpId() {
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
}
Then in the main:
main:
Employee e = new Employee();
e.init(); // otherwise id won't be generated
This is not really convenient because whoever uses creates the Employee object will have to call init on it. In this case you might consider a factory method:
public class Employee {
private final String name;
private String empId;
private Employee(String name) {
this.name = name;
}
public static Employee create(String name) {
Employee emp = new Employee(name);
emp.init();
}
private void init() {
setupId();
}
private void generateEmpId() {
Random rand = new Random();
int randint = rand.nextInt(100000);
char subId = 'E';
employeeID = subId + String.valueOf(randint);
this.employeeID = employeeID;
}
}
Notice that the constructor is private now, which means that the only way to create Employee from main is using the create method. The init method also went private:
main:
Employee emp = Employee.create("John");
// the id is created - no need to remember to call "init" like in the previous example

Employee class should look like:
public class Employee {
private String employeeID;
public Employee() {
}
public void setEmployeeId(String employeeID){
this.employeeID = employeeID;
}
public String getEmployeeId(){
return employeeID;
}
}
From the class you want to assign new id, use the following:
public String generateId(String subId) {
Random rand = new Random();
int randint = rand.nextInt(100000);
return subId.concat(String.valueOf(randint));
}
Employee employee = new Employee();
employee.setEmployeeId(generateId('E'));

public class Emp {
private String id;
public Emp(){
id=getRandomId();
}
public void setId(String x){
id=new String(x);
}
public String getId(){
return new String (id);
}
public static String getRandomId(){
Random rand = new Random();
return "E"+rand.nextInt(100000);
}
}
getRandomId will return a random id.

Related

Create ID for each object in a ListObjectClass

I have two classes, my object class, and the ListObjectClass.
In my constructor of ListObjectClass I create an array of an object looking like this:
private ObjectClass[] name;
And I have to make an ID for each ObjectClass, but I don't know how can I do that, do I need to make a getID() and setID() on ObjectClass?
Constructor of ListObject Class:
private int id;
private float pes;
private int nRegistres;
private RellotgeObjecte[] rellotge;
public LlistaRegistreEsportiu(int n) {
this.nRegistres = 0;
rellotge = new RellotgeObjecte[n];
}
You can pass the ID as an argument of the constructor:
public LlistaRegistreEsportiu(int n, int id) {
this.nRegistres = 0;
rellotge = new RellotgeObjecte[n];
this.id = id;
}

Hiring a person by surname

Could anyone help me fix the below-attached code? I've written a Java method that hires a person by surname, and what I mean by that is that the value passed in the method should be the last name of an object reference (an object of a class Employee which we desire to hire in the company).
However, the program is complaining that the surname cannot be resolved to a type. Now, getSurname() is a method of a private instance variable defined in Employee which is an abstract class (and a superclass for two subclasses Worker and Officer, but that's irrelevant to the problem). Anyone willing to give me a hand?
public class CompanyArrayList {
private ArrayList<Employee> arrayList;
public CompanyArrayList(int employeeNumber) {
ArrayList<Employee> arrayList = new ArrayList<Employee>(employeeNumber);
}
public String hire(Employee employee.getSurname()) { // the object of this class will be generated in the "main" method.
for (int i = 0; i < employeeNumber; i++) {
if (!arrayList.contains(employee.getSurname())) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
} // WHY?
}
public String fire(Employee employee) {
for (Employee i : arrayList) {
if (employee.getSurname().equals(i.getSurname())) {
arrayList.remove(employee);
return "Fired"; // returns nothing and terminates the method execution.
}
}
return "The person of the" + employee.getSurname() + " surname doesn't work in the company";
}
}
public abstract class Employee {
private String surname;
private float contract; // contract = workperiod
public String getSurname() { // Here we're asking about a surname of an employee
return surname;
}
public float getContract() {
return contract;
}
public Employee(String surname, float contract) {
this.surname = surname;
this.contract = contract;
}
public abstract float pay();
public abstract String group();
}
Change String hire(Employee employee.getSurname()) to String hire(Employee employee).
Edit:
About the Employee that you want to hire() by surname (which I've explained you why this is a bad idea) do this:
public String hire(Employee employee) {
for (int i = 0; i < arrayList.size(); i++) { // you had employeeNumber instead of arraylist.size() but hire() method does not know anything about that variable
Employee temp = arraylist.get(i);
if (temp.getSurname().equals(employee.getSurname)) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
}
}

Java ATM Machine- How do I acess an object(Bank account) from a user input(Enter an account number)

In my Java class we have to create two objects that are supposed to be bank accounts.
Example:
Account account1 = new Account();
account1.setName("Isabella");
account1.setBalance(50.00);
Account account2 = new Account();
account2.setName("Oscar");
account2.setBalance(1000.00);
My prof wants us to be able to display the information when a user picks an option, like "Account Information". But before that point, the user has to put in an account number, specifically 101 or 102. The problem is that I don't understand how to assign this number in a way that will choose that method.
//accesor methods
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
public double getBalance() {
return this.balance;
}
public double getInterest() {
return this.interest;
}
//mutator methods
public void setName(String name) {
String accName = null;
this.name = accName;
}
public void setBalance(double balance) {
double accBalance = 0;
this.balance = accBalance;
}
public void setInterest(double interest) {
double monthlyInterest = 0;
this.interest = monthlyInterest;
}
These are my accessors and mutators, I don't know if it's related though? My prof said we need to make one for ID(the account number) but to only make an accessor for that one....
Dose your professor told anything about if you can change the class constructor or not?
You can change the class constructor of class Account as following:
Account(int acId)
{
this.id = acId;
}
Then call constructor in your code like:
Account account1 = new Account(101);
...
Account account2 = new Account(102);
Sounds like the account id should be required and immutable.
You'll want to add it to your Account constructor, eg
public class Account {
public final int id; // final means this cannot be changed once assigned
// other fields
public Account(final int id) {
this.id = id;
}
// getters, setters, etc
}
Now you can get (access) the account id via
account1.id
Some people aren't a fan of public final properties so you could always make a getter for it
public class Account {
private final int id;
// other fields
public Account(final int id) {
this.id = id;
}
public int getId() {
return id;
}
// getters, setters, etc
}
As for retrieving accounts by ID, sounds like you need a bank with some sort of map of id -> account. For example
public class Bank {
private Map<Integer, Account> accounts = new HashMap<>();
public void addAccount(final Account account) {
accounts.put(account.id, account); // or account.getid()
}
// using Optional as I cannot stand #Nullable return types
public Optional<Account> getAccount(final int id) {
return Optional.ofNullable(accounts.get(id));
}
}

Multiple values in a single data-field?

I have created the class:
public playlists(int ID, String nam, int lengt, int movi) {
// TODO Auto-generated constructor stub
playlistID = ID;
name = nam;
length = lengt;
movieID = movi;
}
The data-field movieID of object playlists needs to store multiple values. I was wondering how I could do this.
As some comments already say: Use an ArrayList or an Array
Use ArrayList to store as many objects as you wish (theoretically)
Use Array if you know the exact number ob objects you want to store
ArrayList<Integer> musicIDs= new ArrayList();
public playlists(int ID, String nam, int lengt, int movi) {
// TODO Auto-generated constructor stub
playlistID = ID;
name = nam;
length = lengt;
movieIDs.add(movi);
}
My codeblock just makes sense if you add some musicids later on to this class.
If you create a new instance of this class and still want all musicids you should use static:
static ArrayList<Integer>...
EDIT:
Thats how i would do it :
public class Main()
{
private Playlist playlist = new Playlist();
public void main(String[] args)
{
MovieInf omi = new MovieInfo(1,"a",2,3);
playlist.add(mi);
mi = new MovieInfo(2,"b",3,4);
playlist.add(mi);
System.out.println(Playlist.getSizeOfList()); // prints "2"
}
}
public class MovieInfo()
{
private int ID,length,movi;
private String name;
public MovieInfo(int ID, String nam, int lengt, int movi) {
this.ID= ID;
this.name= name;
this.length= length;
this.movi= movi;
}
}
public class Playlist()
{
private ArrayList<MovieInfo> movies = new ArrayList();
public void add(MovieInfo mi)
{
movies.add(mi);
}
public int getSizeOfList()
{
return movies.size();
}
}

Java Subclasses last instance overwriting values

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

Categories