Please explain what "MANAGER static employee" means.
I did everything except changeManager, how can I implement it ?
public Employee(){
this.id=-1;
this.year=-1;
salary=-1;
name="NA";
department="NA";
}
public Employee(int id ,String name ,String depatment, int year,double salary){
Employee Employee=new Employee();
Employee.setid(id); Employee.setname(name); Employee.setdepartment(depatment); Employee.setyear(year); Employee.setsalary(salary);
}
As in Java a static attribute in UML is an attribute of the class itself, rather than an attribute of instance, that means there is only one manager 'shared' by all the instances. Of course its type is Employee, so in Java :
private static Employee MANAGER;
by default the class has no manager because MANAGER is null.
Note the presence of 'static' in the diagram is abnormal and does not follow the norm, like for the operation changeManager the line for the attribute is underlined, that is the way to say an attribute/operation is static in UML
The definition of isManager is trivial :
public boolean isManager() { return this == MANAGER; }
Note may be the class does not have yet a manager, in that case MANAGER is null, and to call isManager(null) is the way to check if the class has a manager
The definition of changeManager is also trivial :
public static void changeManager(Employee newManager) { MANAGER = newManager; }
Note that allows to have no manager calling that operation with null
Example with few methods/attributes :
Employee.java
class Employee {
private String name;
private int id;
private static Employee MANAGER;
public Employee(String n, int i) {
name = n;
id = i;
}
public boolean isManager() {
return this == MANAGER;
}
public static void changeManager(Employee e) {
MANAGER = e;
}
}
Main.java
class Main {
public static void main(String[] args) {
Employee e1 = new Employee("e1", 1);
Employee e2 = new Employee("e2", 2);
System.out.print("e1.isManager() = ");
System.out.println(e1.isManager());
System.out.print("e2.isManager() = ");
System.out.println(e2.isManager());
System.out.println("do 'Employee.changeManager(e1)'");
Employee.changeManager(e1);
System.out.print("e1.isManager() = ");
System.out.println(e1.isManager());
System.out.print("e2.isManager() = ");
System.out.println(e2.isManager());
System.out.println("do 'Employee.changeManager(e2)'");
Employee.changeManager(e2);
System.out.print("e1.isManager() = ");
System.out.println(e1.isManager());
System.out.print("e2.isManager() = ");
System.out.println(e2.isManager());
System.out.println("do 'Employee.changeManager(null)'");
Employee.changeManager(null);
System.out.print("e1.isManager() = ");
System.out.println(e1.isManager());
System.out.print("e2.isManager() = ");
System.out.println(e2.isManager());
}
}
Compilation, execution :
pi#raspberrypi:/tmp $ javac Main.java Employee.java
pi#raspberrypi:/tmp $ java Main
e1.isManager() = false
e2.isManager() = false
do 'Employee.changeManager(e1)'
e1.isManager() = true
e2.isManager() = false
do 'Employee.changeManager(e2)'
e1.isManager() = false
e2.isManager() = true
do 'Employee.changeManager(null)'
e1.isManager() = false
e2.isManager() = false
pi#raspberrypi:/tmp $
Related
I want to use the object person in the Librarian_Interface class, but this call the method login() in a loop. I think there is something I don't understand with java instance and I tried to get person with a constructor or methode but in vain. Thanks !
public class Login_Interface {
Person person;
public Login_Interface() {
db.initConnection();
person = login(db, in);
if (person != null)
{
Librarian_Interface a = new Librarian_Interface();
a.run();
}
}
public void run() {
}
public static Person login(DbConnection db, Scanner sc) {
Persons.setDbConnection(db);
Persons persons = Persons.getInstance();
System.out.print("\nEnter your Phone Number : ");
String phone = sc.nextLine();
System.out.print("\nEnter your Password : ");
String password = sc.nextLine();
return persons.login(phone, password);
}
}
public class Librarian_Interface {
public Librarian_Interface() {
// What I want
// System.out.print(person); or person.getAge(); ...
All you have to do is pass the person object to the Librarian_Interface constructor. then you can call methods getAge on it, etc.
public class Librarian implements Runnable {
private final Person person;
public Librarian(Person person) {
this.person = person;
}
#Override
public void run() {
int age = person.age();
// ... whatever else
}
}
By the way, the convention in Java is to use upper camel case for class names, with no underscores. So it would be better to name the class LibrarianInterface. Also, it's probably not the best idea to call it LibrarianInterface if it is in fact a class and not an interface.
Since Librarian has a public run method, it's a good idea to have it implement Runnable so that users of the class see how it is meant to be used.
In this application we have the Automovel class:
public class Automovel {
private String marca;
private String matricula;
private String anoConstrucao;
private Motor motor;
private int preco = 0;
}
(with their builders, getters and setters) and there is a class called Motor that is an attribute of the Automovel class.
Motor Class:
private int potencia;
public Motor() {}
public Motor(int potencia){
this.potencia = potencia;
}
public int getPotencia() {return this.potencia;}
public void setPotencia(int potencia) {
this.potencia = potencia
}
There are also 2 subclasses of this class (MotorEletrico and MotorCombustao):
Motor Elétrico:
public class MotorEletrico extends Motor {
private int autonomia;
public MotorEletrico() {}
public MotorEletrico(int potencia, int autonomia) {
super(potencia);
this.autonomia = autonomia;
}
public int getAutonomia() {
return autonomia;
}
public void setAutonomia(int autonomia) {
this.autonomia = autonomia;
}
}
Motor Combustão:
public class MotorCombustao extends Motor{
private int cilindrada;
private String combustivel;
public MotorCombustao(){}
public MotorCombustao(int potencia, int cilindrada, String combustivel){
super(potencia);
this.cilindrada = cilindrada;
this.combustivel = combustivel;
}
public int getCilindrada(){
return cilindrada;
}
public void setCilindrada(int cilindrada){
this.cilindrada = cilindrada;
}
public String getCombustivel(){
return combustivel;
}
public void setCombustivel(String combustivel){
this.combustivel = combustivel;
}
}
I store a car with an X engine in an array of Automovel objects, but when I try to access the getters and setters of the subclass (MotorCombustao / MotorEletrico), only the gets and sets of the mother class (Motor) appears. My problem is that I can't access the getters and setters of the motor subclasses.
Here's an example of what I tried:
Automovel arrayteste[] = new Automovel[49];
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste[0] = automovel1;
System.out.println(arrayteste[0].getMotor().getPotencia()); //Here, I can't Do .getAutonomia
Short answer
You need to cast
System.out.println(((MotorElettrico)(arrayteste[0].getMotor())).getAutonomia());
TL;DR
When you wrote
Motor motor1 = new MotorElettrico();
you are using polymorphism.
This is very useful when, for example you, have a list of Motor that contains more then one motor type and for all of this you want to print the potencia.
Then you can write something like this:
List<Motor> list = Arrays.asList(new MotorElectico(), new MotorCombustao());
// ----- some set
print(list);
where print method is something like this:
public void print(List<Motor> list){
for(Motor m : list){
System.out.println(String.format("Potencia %d", m.getPotencia()));
}
}
This happens because a MotorElectico IS A Motor and upcasting (casting to supertype) is always allowed.
In your case, you have to do downcasting: you are telling to a compilator that arraytest[0].getMotor() contains a Motor but this Motor is actually a MotorElectrico: you are asking to compilator to trust you. If at compile-time arraytest[0].getMotor() should not be a MotorElectrico you'd get a ClassCastException.
You need to cast the reference of the parent class to the corresponding child class if you want to access a method which is not inherited from the parent class e.g. the method, getAutonomia() is not inherited from Motor and therefore, you need to cast the reference of Motor to MotorEletrico before you can access getAutonomia(). Some more useful code is given below:
public class Main {
public static void main(String[] args) {
Automovel arrayteste[] = new Automovel[2];
Motor motor;
motor = new MotorEletrico(5, 10);
arrayteste[0] = new Automovel("Opel", "xx-12-xx", "2000", motor, 2000);
motor = new MotorCombustao(7, 4, "xx-yy-zz");
arrayteste[1] = new Automovel("Opel", "xx-08-xx", "1995", motor, 1995);
for (Automovel automovel : arrayteste) {
motor = automovel.getMotor();
if (motor instanceof MotorEletrico) {
System.out.println(((MotorEletrico) motor).getAutonomia());
}
if (automovel.getMotor() instanceof MotorCombustao) {
System.out.println(((MotorCombustao) motor).getCilindrada());
System.out.println(((MotorCombustao) motor).getCombustivel());
}
}
}
}
Output:
10
4
xx-yy-zz
[Update: the following update is based on your comment]
Another way to iterate arrayteste is as given below:
for (int i = 0; i < arrayteste.length; i++) {
if (arrayteste[i] != null) {
motor = arrayteste[i].getMotor();
if (motor instanceof MotorEletrico) {
System.out.println(((MotorEletrico) motor).getAutonomia());
}
if (arrayteste[i].getMotor() instanceof MotorCombustao) {
System.out.println(((MotorCombustao) motor).getCilindrada());
System.out.println(((MotorCombustao) motor).getCombustivel());
}
}
}
You are familiar with the Liskov substitution principle, I assume.
If you don't know the type of motor, you can write a statement that asks each instance of the Automovel array arraytest[i] what class it is.
For example:
List<Automovel> arrayteste = new ArrayList<>();
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste.add(automovel1);
Motor motor = new Motor();
String motorClass;
String[] motorTypes = {"MotorEletrico", "MotorCombustao"};
Set<String> motorClasses = new HashSet<>(Arrays.asList(motorTypes));
for (int i = 0; i < arrayteste.size(); i++)
{
motorClass = arrayteste.get(i).getMotor().getClass().getName();
if (motorClasses.contains(motorClass))
{
if (motorClass.equals("MotorEletrico"))
{
motor = (MotorEletrico)(arrayteste.get(i).getMotor());
}
else if (motorClass.equals("MotorCombustao"))
{
motor = (MotorCombustao)(arrayteste.get(i).getMotor());
}
System.out.println("Automovel #" + i + " : " + motor.getPotencia());
}
else
{
System.out.println("Não sei que classe de motor é esse . . .");
}
}
}
But it might be better to explore the class design more closely.
Possibly try to use interfaces.
I have a super class, sub class, and a tester class. Can anyone help with what I'm doing wrong?
Here is what I need in my tester class-
1. Create objects of Manager and Employee.
Create a function revise salary to revise the salary set in the constructor of Manager or Employee. (Use concept of polymorphism)
Use the object’s Display functions to print the relevant information pertaining to the object’s class.
Here are my classes
Superclass:
public class Employee {
private int employeeNumber;
private String employeeName;
private double employeeSalary;
public Employee(int employeeNumber, String employeeName, double employeeSalary) {
this.employeeNumber = employeeNumber;
this.employeeName = employeeName;
this.employeeSalary = employeeSalary;
}
public double getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(double employeeSalary) {
this.employeeSalary = employeeSalary;
}
public void display(){
System.out.println("Employee Number: "+ employeeNumber +"\n"
+ "Employee Name: " + employeeName + "\n"
+ "Employee Salary: " + employeeSalary);
}
}
Subclass:
public class Manager extends Employee {
private int rewards;
public Manager(int employeeNumber, String employeeName, double employeeSalary) {
super(employeeNumber, employeeName, employeeSalary);
}
public void display() {
super.display();
System.out.println(rewards);
}
}
Tester:
public class Test {
public static void main(String [] args) {
Manager manager = new Manager(11111, "Elon Musk", 42344);
manager.display();
Employee employeeOne = new Employee(324, "Bob Den", 3522);
Employee employeeTwo = new Employee(44, "Tim Pipe", 4234 );
Employee employeeThree = new Employee(42, "Asif Blar", 4321);
private void reviseSalary() {
double employeeSalary = manager.getEmployeeSalary();
manager.setEmployeeSalary(employeeSalary +(employeeSalary /10));
manager.display();
}
}
}
**My issue:
I am getting errors on my test class. When I create a manager object, it says the constructor is undefined. Also, for my private void "reviseSalary", it says I cannot use void
Can anyone tell me what I'm doing wrong, and help in creating my reviseSalary function if possible
Thanks
Just put your reviseSalary out of main method.
This error happens because Java does not support nested function.
public class Test {
public static void main(String [] args) {
Manager manager = new Manager(11111, "Elon Musk", 42344);
manager.display();
Employee employeeOne = new Employee(324, "Bob Den", 3522);
Employee employeeTwo = new Employee(44, "Tim Pipe", 4234 );
Employee employeeThree = new Employee(42, "Asif Blar", 4321);
reviseSalary(manager);
}
private static void reviseSalary(Manager manager) {
double employeeSalary = manager.getEmployeeSalary();
manager.setEmployeeSalary(employeeSalary +(employeeSalary /10));
manager.display();
}
}
This will be your output:
Employee Number: 11111
Employee Name: Elon Musk
Employee Salary: 42344.0
Employee Number: 11111
Employee Name: Elon Musk
Employee Salary: 46578.4
I see two main problems with your code:
1) You declare method reviseSalary() inside main() method. Java doesn't allow you to declare method inside of the other method.
You should rather declare it outside of the main() method and add a keyword static to let you call this method without the need of having an instance of your Test class. Otherwise, if you don't declare this method as static, you would need an instance of Test class and have to call reviseSalary() on this instance like this:
Test t = new Test() ;
t.reviseSalary();
2) You declared this field in the Manager class: private int rewards, but you don't declare any setter method to assign any value to that field.
I'm a beginner in Java programming, I tried everything I could but I cant seems to troubleshoot my problem.
The problem Im facing is the getCardID() methods keep returning null value, the getTokenBalance() seems to work fine, or do i need special code to return a string value from getCardID()?
Any help is very much appreciate.
This is Prepaidcard.java class:
class PrepaidCard {
private String cardID;
private int tokenBalance;
public PrepaidCard(String id) { // My First Constructor
String cardID = id ;
}
public PrepaidCard(String id, int token) { // My Second Constructor
String cardID = id;
tokenBalance = token;
}
public void addToken(int token) { // Methods
tokenBalance =token+tokenBalance;
}
public void deductToken(int token) { // Methods
tokenBalance=tokenBalance-token;
}
public int getTokenBalance() { // Methods
return tokenBalance;
}
public String getCardID() { // Why does this method keep returning null value?
return cardID;
}
}
This is the class use to test prepaidcard.java
import java.util.*;
class testprepaid {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert card1 id : ");
String newid = sc.nextLine(); // my scanner class that read user input in String
System.out.print("Insert card2 id : ");
String newid2 = sc.nextLine(); // my scanner class that read user input in String
System.out.print("Enter Card2 initial token : ");
int itoken = sc.nextInt();
PrepaidCard card1 = new PrepaidCard(newid); // object created base on 1st & 2nd Constructor
PrepaidCard card2 = new PrepaidCard(newid2,itoken);
System.out.println("Card1 ID: " + card1.getCardID()); // the method return null when called
System.out.println("Card1 token balance : " + card1.getTokenBalance());
System.out.println("Card2 ID: " + card2.getCardID()); // and this
System.out.println("Card2 token balance : " + card2.getTokenBalance());
And other line contains no error so I didn't add them.
You can see my runtime error here.
In your constructor, you declared a new local variable:
public PrepaidCard(String id, int token) {// My Second Constructor
String cardID = id; //This should be cardID = id;
tokenBalance = token;
}
Depending on your IDE, you may enable warnings that could tell you about uninitialized private members.
String cardID = id ;
should be a instance variable.
So remove local declaration of String cardID -
public PrepaidCard(String id){ //My First Constructor
cardID = id ;
}
I have a main class, what looks like this:
class Main {
public static void main (String[] args) {
Mobil one = new Mobil ("xxxxxx", "yyyyyy", 00000001, true);
Mobil two = new Mobil ("yyyyyy", "xxxxxx", 10245624, false);
one.touchcontrol();
two.touchcontrol();
}
}
And I have this Mobil class:
class Mobil {
String type;
String manufactureat;
int modellnumber;
boolean touchtype;
public Mobil (String manufacturer, String inittype, int number, boolean touch) {
manufacturer = manufactureat;
inittype = type;
number = modellnumber;
touch = touchtype;
}
public void touchcontrol() {
if (touchtype == false)
{
System.out.println("This model, has not got Touchscreen!");
}
else
{
System.out.println("This model, has Touchscreen!");
}
}
But when I run the program and invoke the one.touchcontrol(); and two.touchcontrol(); it shows that no model has got Touchscreen. I don't know what I missed.
You need to swap the variable assignments in the constructor.
manufactureat = manufacturer;
type = inittype;
modellnumber = number;
touchtype = touch;
In variable assignments in Java (and in pretty much all other languages), the left hand will retrieve the value of the right hand.
See also:
The Java Tutorials - Language Basics - Assignment operators
You are incorrectly assigning values to variables in your constructor...
public Mobil (String manufacturer, String inittype, int number, boolean touch) {
manufacturer = manufactureat; // should be manufactureat = manufacturer;
inittype = type; //same problem
number = modellnumber; // same here
touch = touchtype; // and here
}