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.
Related
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 $
I'm new to Java and honestly its OOP focus is quite taxing for me at the moment.
For an Uni project where we're meant to practice this focus, I'm tasked with creating at least 2 classes:
One class should be for an airline customer and the other class should contain methods to register their purchase.
I have a main file, a Persona (Person) class, and a RegistroCompra (Purchase registration) class. Person is supposed to have all of the following attributes, which I'm handling as private variables so that every instance of Person can get one of their own.
(The attributes being asked for are stuff like personal data, ticket number, seat number and such)
public class Persona {
private String nombrePasajero;
private String apellidoPasajero;
private String generoPasajero;
private String pasaportePasajero;
private String numTiquetePasajero;
private String numVueloPasajero;
private String destinoPasajero;
private String asientoString;
private int precioBoleto;
private int edadPasajero;
private int numAsientoPasajero;
//Constructor
public Persona(String nombre, String apellido, String genero, int edad, String pasaporte) {
nombrePasajero = nombre;
apellidoPasajero = apellido;
generoPasajero = genero;
pasaportePasajero = pasaporte;
edadPasajero = edad;
}
public void setDestino() {
destinoPasajero = RegistroCompra.obtenerDestino();
}
And my RegistroCompra class, which is meant to set the data related not to personal information but to the information of destination, flight number and such. All of the data set in RegistroCompra has to be fetched by Persona, because only Persona will be printed in main to verify all of the information.
public class RegistroCompra {
private String destino;
public void seleccionarDestino() {
Scanner input = new Scanner(System.in);
System.out.println("Por favor digite el destino, las opciones actuales son Nicaragua o Panama\n");
String destino = input.nextLine();
}
public String obtenerDestino() {
return destino;
}
}
However, I get an error at the Persona.setDestino() method, saying "non-static method obtenerDestino cannot be referenced from astatic context"
I don't understand why this is going on. If I try to turn RegistroCompra.obtenerDestino() into a static method, I get an error because "destino is a non static variable", but it's being defined as public in the RegistroCompra class...
You have to do something like below:
public class Persona {
...
//You should have instance of RegistroCompra
RegistroCompra registraCompra = new RegistroCompra();
public void setDestino() {
//Option 1: Explicitly call the method
registraCompra.seleccionarDestino();
destinoPasajero = registraCompra.obtenerDestino();
}
}
public class RegistroCompra {
private String destino;
public RegistroCompra(){
//Option 2 : Call the method in constructor
registraCompra();
}
public void seleccionarDestino() {
...
//Set the input to the class level variable destino
this.destino = input.nextLine();
}
public String obtenerDestino() {
return this.destino;
}
}
You can do this making destino variable and obtenerDestino() method static. Check the below changes to RegistroCompra class:
public class RegistroCompra {
private static String destino;
public void seleccionarDestino() {
Scanner input = new Scanner(System.in);
System.out.println("Por favor digite el destino, las opciones actuales son Nicaragua o Panama\n");
String destino = input.nextLine();
}
public static String obtenerDestino() {
return destino;
}
}
You are calling an instance method without having an instance. You have to instantiate the class (create an instance from that class) before you are able to call instance methods.
I've just started to learn Java a month or so ago, and now have a problem with "non-static variable studentList cannot be referenced from a static context". I'm trying to have a separate method from main to populate the list of students, instead of copy pasting stuff from addStudent for each student; but I cannot get the methods to write to the ArrayList. (Error:(14, 27) java: non-static variable studentList cannot be referenced from a static context). I understand how the array is not static because it has an undefined size, but how could I make it work as is? Is there any better approach? Could I have the array be part of the main method and then have it passed on to addStudent, if so how?
import java.util.ArrayList;
public class Main {
ArrayList<Student> studentList = new ArrayList<>();
public static void main(String []args) {
addStudent("Adam", "Goldsmith", 70, 50);
addStudent("John", "Smith", 20, 40);
addStudent("Lewis", "Peterson", 90, 85);
for (Student obj: studentList){
System.out.println("Name: " + obj.studentForename + " "+ obj.studentSurname);
}
}
public static void addStudent(String forename, String surname, int coursework, int test) {
Student newStudent = new Student(forename, surname);
newStudent.setForename(forename);
newStudent.setSurname(surname);
newStudent.averageMark(70, 65);
studentList.add(newStudent);
}
}
and my "Student" Class:
public class Student {
String studentForename;
String studentSurname;
public Student(String studentForename, String studentSurname) {
setForename(studentForename);
setSurname(studentSurname);
}
// Set forename.
public void setForename(String newForename) {studentForename = newForename;}
// Set surname.
public void setSurname(String newSurname) {studentSurname = newSurname;}
//
public double averageMark(int courseworkMark, int testMark){
return (courseworkMark+testMark)/2;
}
// Grab the forename
public String grabForename(){
return studentForename;
}
// Grab the surname
public String grabSurname(){
return studentSurname;
}
// Grab the full name
public String grabFullName(){
return studentForename + "" + studentSurname;
}
}
Your code should look like this, especially your Student class using java encapsulation
public class Student {
private String studentForename;
private String studentSurname;
private int courseworkMark;
private int testMark;
public Student(String studentForename, String studentSurname, int courseworkMark, int testMark) {
this.studentForename = studentForename;
this.studentSurname = studentSurname;
this.courseworkMark = courseworkMark;
this.testMark = testMark;
}
public void setStudentForename(String studentForename) {
this.studentForename = studentForename;
}
public String getStudentSurname() {
return studentSurname;
}
public void setStudentSurname(String studentSurname) {
this.studentSurname = studentSurname;
}
public String getStudentForename() {
return studentForename;
}
public double averageMark(){
return (this.courseworkMark + this.testMark)/2;
}
public String grabFullName(){
return studentForename + " " + studentSurname;
}
}
And then testing via your Main class :
public class Main {
public static void main(String []args) {
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("Adam", "Goldsmith", 70, 50));
studentList.add(new Student("John", "Smith", 20, 40));
studentList.add(new Student("Lewis", "Peterson", 90, 85));
for (Student obj: studentList){
System.out.println("Name: " + obj.getStudentForename() + " "+ obj.getStudentSurname());
}
}
}
import java.util.ArrayList;
public class Main {
static ArrayList<Student> studentList = new ArrayList<>();
public static void main(String []args) {
addStudent("Adam", "Goldsmith", 70, 50);
addStudent("John", "Smith", 20, 40);
addStudent("Lewis", "Peterson", 90, 85);
for (Student obj: studentList){
System.out.println("Name: " + obj.studentForename + " "+ obj.studentSurname);
}
}
public static void addStudent(String forename, String surname, int coursework, int test) {
Student newStudent = new Student(forename, surname);
newStudent.setForename(forename);
newStudent.setSurname(surname);
newStudent.averageMark(70, 65);
studentList.add(newStudent);
}
}
It was not due to undefined size but was because you were trying to access it without creating an object from a static method.
So just write static before it and it will work.
thought the above answer answers you question, but few words about static vs non static modifiyers in java
Characteristics of Static methods
A static method is called using the class (className.methodName) as opposed to to an instance reference (new instanceOfClass = class; instanceOfClass.methodName.)
Static methods can’t use non-static instance variables: a static method can’t refer to any instance variables of the class. The static method doesn’t know which instance’s variable value to use.
Static methods can’t call non-static methods: non-static methods usually use instance variable state to affect their behaviour. Static methods can’t see instance variable state, so if you try to call a non-static method from a static method the compiler will complaint regardless if the non-static method uses an instance variable or not.
Non-Static methods
A non-static method does not have the keyword static before the name of the method.
A non-static method belongs to an object of the class and you have to create an instance of the class to access it.
Non-static methods can access any static method and any static variable without creating an instance of the class.
So you'd better think if you need to define studentList as static or no, and if modify your code accordingly.
P.S. above written is taken from here
The difference between static (global, class level) and non-static (a instance of that class, an object) is important.
Creating an object by new Main() allows to work on that object and its fields.
The static void main(String[]) is the single entry point to the application.
Inside the main you have access only to static fields and static methods. So that is cumbersome.
package srivastava.arpit; // In a directory path srivastava/arpit/
import java.util.ArrayList;
public class Main {
private ArrayList studentList = new ArrayList<>();
public static void main(String []args) {
Main main = new Main();
main.execute();
}
private void execute() {
addStudent("Adam", "Goldsmith", 70, 50);
addStudent("John", "Smith", 20, 40);
addStudent("Lewis", "Peterson", 90, 85);
for (Student obj: studentList){
System.out.println("Name: " + obj.studentForename + " "+ obj.studentSurname);
}
}
public void addStudent(String forename, String surname, int coursework, int test) {
Student newStudent = new Student(forename, surname);
newStudent.setForename(forename);
newStudent.setSurname(surname);
newStudent.averageMark(70, 65);
studentList.add(newStudent);
}
}
The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.