I have class Employe that has variables like id , name ... and 2 other classes that inherit from Employe : Seller and Cashier.
To calculate their salaries, I created a method in each one of Seller and Cashier but I need to access the name via the name getter method in Employe so I'd have :
System.out.println("The salary is "+Seller.getName() +" is : " +salary);
Once I type that, I get an error sayingI need to make the name variable to static, but I need it as non static since I'm creating multiple objects using the name variable.
Any solution to this problem?
EDIT :
This is the Employe class :
public class Employe {
protected int id;
protected String name;
protected String adresse;
protected int nbrHours;
public Employe () {
}
public Employe (int id, String name, String adresse, int nbHours)
{
this.id=id;
this.name=name;
this.adresse=adresse;
this.nbrHours=nbHours;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setNom(String name) {
this.name = name;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
This is the Seller class :
public class Seller extends Employe {
private int prime;
public Seller (int id, String name, String adresse, int nbHours,int prime)
{
super(id,name,adresse,nbHours);
this.prime=prime;
}
public int getPrime() {
return prime;
}
public void setPrime(int prime) {
this.prime = prime;
}
#Override
public String toString() {
return super.toString() +" [prime=" + prime + "]";
}
public void salaireSeller ()
{
int salaire = 0;
if(nbrHours<160)
{
salaire = nbrHours * 10 + prime;
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
}
else if(nbrHours >160)
{
int Extra= (160 - nbrHours) * 12;
int salaire1 = 160 * 10000 + prime;
salaire= Extra + salaire1;
System.out.println("La salaire de "+Seller.getName() +" est : " +salaire);
}
}
In the Main class I created a Seller object :
Seller Sel1 = new Seller(2, "Alex", "Miami", 18, 200);
now I want to calculat its salary using the SalaireSeller() method in the Main class of course :
Sel1.salaireSeller();
but in the Seller class :
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
it says I need to set Name to static, this will give every object the same name
You need a Seller instance, to call getName() and getSalary() on.
Seller s = new Seller();
// ...
System.out.println("The salary is " + s.getName() +
" is : " + s.getSalary());
You're certainly trying to access an instance variable from a static method.
What you want to do here is to create an instance of your class, then call the getName() method on the object created.
Seller sell = new Seller();
sell.setName("Jean-Paul"); // This is just an example
System.out.println("His name is " + sell.getName()); // Prints : His name is Jean-Paul
I figuered out a solution, I just need to add the name to the toString() method in class Employee, then add the salary variable to the toString() method in Seller class, without System.out.println(..) in SalaireSeller().
or instead of Seller.getName(), I use this.getName() and it works.
Related
I have created a class employee in Java, where each object of the class stands for a staff. The objects take 3 parameters - Name, Dept. and Salary. The program looks like this:
public class employee
{
String name;
int salary;
String dept;
employee staff1 = new employee("x","IT",100000);
employee staff2 = new employee("y", "HR", 200000);
public employee(String n, String d, int s)
{
this.name= n;
this.salary= s;
this.dept = d;
}
public static void main (String args [])
{
}
public void Display()
{
}
}
I want to make a method (the Display method in the code) which takes the object name as a parameter (the code does not have a parameter) and returns (or prints) its data values. Please also tell me what should come in the main method. Thanks in advance.
You can use this -
public class employee {
String name;
int salary;
String dept;
public employee(String n, String d, int s) {
this.name = n;
this.salary = s;
this.dept = d;
}
public static void main(String args[]) {
employee staff1 = new employee("x", "IT", 100000);
employee staff2 = new employee("y", "HR", 200000);
Display(staff1);
Display(staff2);
}
public static void Display(employee object) {
System.out.println("name='" + object.name + '\'' +
", salary=" + object.salary +
", dept='" + object.dept + '\'');
}
}
Here, I have a superclass called 'Staff'. My main method is in a separate class called 'Program_2A'. The filename given is Program_2A.java. Eclipse is showing an error in the second line of the program saying
Link all references for a local rename (does not change references in other files)
I don't understand what's wrong by having the main class, not as a superclass.
Here is the code:
import java.util.*;
public class Staff {
private int Staff_ID;
private String Name;
private int Phone;
private int Salary;
public Staff(int staff_id, String name, int phone, int salary)
{
Staff_ID = staff_id;
Name = name;
Phone = phone;
Salary = salary;
}
public void display()
{
System.out.println("\t" + Staff_ID + "\t" + Name + "\t" + Phone + "\t" + Salary);
}
}
class Teaching extends Staff
{
private String Domain;
private int Publication;
public Teaching(int staff_id, String name, int phone, int salary, String domain, int publication) {
super(staff_id,name,phone,salary);
Domain = domain;
Publication = publication;
}
public void display() {
super.display();
System.out.println("\t" + Domain + "\t" + Publication);
}
}
class Technical extends Staff
{
private String Skills;
public Technical(int staff_id, String name, int phone, int salary, String skills) {
super(staff_id,name,phone,salary);
Skills = skills;
}
public void display() {
super.display();
System.out.println("\t" + Skills);
}
}
class Contract extends Staff
{
private int Contract;
public Contract(int staff_id, String name, int phone, int salary, int contract) {
super(staff_id,name,phone,salary);
Contract = contract;
}
public void display() {
super.display();
System.out.println("\t" + Contract);
}
}
class Program_2A {
public static void main(String[] args) {
Staff St[] = new Staff[3];
St[0] = new Teaching(1, "ABC", 1234, 10000, "CSE", 3);
St[1] = new Technical(2, "DEF", 5678, 200000, "C++");
St[2] = new Contract(3, "GHI", 9012, 50000, 3);
System.out.println("STAFF ID \t NAME \t PHONE \t SALARY \t DOMAIN \t PUBLICATIONS \t SKILLS \t PERIOD");
for(int i=0;i<3;i++) {
St[i].display();
System.out.println();
}
}
}
In Java, one file can only contain one public class.
So please change class Program_2A to public class Program_2A and remove public keyword before Staff class.
Inheritance is not completely working for me as the extra variables outside the inheritance class are not being displayed. When I input the employee details and input the wage it is accepted. But then it is not shown when I list all employees in database or when searching for an employee
public class Employee extends Person {
public Employee(){ }
public Employee (int id, int wage, String name, String surname){
super(id,name,surname);
this.wage = wage;
}
private int wage;
public void SetWage(int wg){
wage=wg;
}
public int GetWage (){
return wage;
}
public String toString(){
return "ID: " + this.GetId() + "\n"
+ "Name:" + this.GetName() + "\n"
+ "Surname:" + this.GetSurname() + "\n"
+ "Wage: " + this.GetWage();
}
}
Similarly the client class is not working. Also here is the code for the person class
public class Person{
public Person(){
pId = 0;
pName = "";
pSurname = "";
}
public Person (int id, String nm, String sn) {
pId = id;
pName = nm;
pSurname = sn;
}
private int pId;
private String pName;
private String pSurname;
public int GetId(){
return pId;
}
public void SetId(int id){
pId= id;
}
public String GetName(){
return pName;
}
public void SetName(String nm){
pName = nm;
}
public String GetSurname (){
return pSurname;
}
public void SetSurname(String sn){
pSurname = sn ;
}
public String ToString(){
return "ID: " + this.GetId() + "\n"
+ "Name:" + this.GetName() + "\n"
+ "Surname:" + this.GetSurname();
}
}
Any suggestions?
First of all, order your class as follows: fields, constructors, methods. Try not to have constructors before the fields, it's rather hard to read.
Also, just like paisanco noted out in the comments - try to ask more specific questions, it's not easy to understand what is the problem.
Last thing - if I understand right, you probably can't access Person class fields, such as:
private int pId;
private String pName;
private String pSurname;
This is most likely problem of how you create your object.
Instead of
Emplyee emp = new Employee();
Try creating employee object in such manner:
Person pers = new Employee();
This should fix this and you should be able to access person class fields aswell.
And if you after that would like to access employee fields like wage and so on, you should cast the object to Employee object, e.g:
if (pers instanceof Employee) {
((Employee) pers).getWage();
}
If you are trying to use it in the following way:
Person employee = new Employee()
you will not be able to use SetWage and GetWage functions because they are not part of Person object. If you want to use work that way you can declare them as abstract functions in Person class of instantiate your object differently: Employee employee = new Employee()
Got an error at : Movie m = new Movie(id, name, cost);
"cannot find symbol - var cost"
cost is set only when user insert input and cannot put actual value e.g.200.00
What should I put as argument?
Also, Session can only be created if user enters correct movie ID.
How do I match compare input(int) to an array?
Any help will be appreciated. Explanation is also important for me
Movie Class:
private void addMovie()
{
System.out.println("Setup a Movie");
int id = movies.setId();
String name = In.readString("Enter Movie Name: ");
double cost = In.readDouble("Enter Movie Cost:" );
Movie movie = new Movie(id, name, cost);
movies.add(movie);
menu();
}
Session Class:
private void addSession()
{
System.out.println("Add a Session");
int id = sessions.setId();
String name = In.readString("Enter Session Name: ");
int movieId = In.readInt("Enter Movie id:" );
**//match input with id array**
int theatreId = In.readInt("Enter Theatre id:" );
**//match input with theatre id array**
String sessionTime = In.readString("Enter Session Time - 0 for 9am, 1 for 12noon, 2 for 3pm or 3 for 6pm: ");
double GoldSeatsPrices = In.readDouble("Enter Prices fro Gold Class Seats:");
double ReguSeatsPrices = In.readDouble("Enter Prices for Regular Seats:");
Movie m = new Movie(id, name, cost);
Session session = new Session(id, name, m);
sessions.add(session);
menu();
}
Movie Class:
public class Movie extends Record
{
private double cost;
public Movie(int id, String name, double cost)
{
super(id, name);
this.cost = cost;
}
public double getCost()
{
return cost;
}
public String toString()
{
return "Movie: "+ super.toString() + " cost: $"+ cost;
}
}
Records Class: (super.):
import java.util.*;
/**
* class Records - complete
*/
public class Records
{
protected LinkedList<Record> records = new LinkedList<Record>();
protected int id = 0;
protected Record find(int id)
{
for(Record record: records)
{
if (record.matches(id))
return record;
}
return null;
}
protected void add(Record record)
{
records.add(record);
}
public int size()
{
return records.size();
}
public void show()
{
System.out.println(toString());
}
public String toString()
{
String str = "";
for(Record record : records)
str += record.toString() + "\n";
return str;
}
}
Record:
/**
* class Record - complete
*/
public class Record
{
protected int id;
protected String name;
public Record(int id, String name)
{
this.id = id;
this.name = name;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public boolean matches(int id)
{
return this.id == id;
}
public String toString()
{
return id + " " + name;
}
}
To the first question: There is no variable cost within addSession(). If you have not defined an attribute cost within Session then this is the problem.
To the second question: I am not quite sure that I understand your problem correctly. You have an int[] values and want to know, whether a given int x is within that array? If so, you can achieve this with this code snippet:
for (int value : values) {
if (value == x) {
// Put code, that should be executed when the value is found, here
}
}
Can you place the Super class Record also in your question?
Probably, you need to check the super constructor, which is differing from your sub class constructor.
I am trying to figure out Inheritance and Arrays in Java and I am trying to get these classes to work together. I believe I have the Inheritance down, but I am still struggling with the array part.
There are three files: 1. Person.java -base class 2. Student.java -a derived class of Person.java 3. Family.java -not quite sure, I think it's its own base class
Person.java has two instance variables, String name and int age, and an assortment of constructors, toString, equals, and set/get methods
Student.java, again, a derived class of Person, by definition will have all the stuff contained within Person, as well as two more instance vars, String major, and double gpa. This class also have get/set methods for major and gpa, an equals method that compares one class student with another class student, and I believe it's called an overidden method of toString that returns name, age, major, and gpa all in one string.
Lastly, Family.java is where the main method resides. It creates an array of type Person, adds "Persons" to this array, then outputs them.
I am getting an error that says: "main" java.lang.ArrayIndexOutOfBoundsException: 8
I can not figure out why this program is not working properly and would appreciate any help to figure this out. Thank you.
Person.java Class
public class Person
{
private String name;
private int age;
public Person()
{
name = "John Smith";
age = 1;
}
public Person(String n, int a)
{
name = n;
age = a;
}
public String toString()
{
return ("Name: " + getName() + ", Age: " + age + " ");
}
public boolean equals(Person otherPerson)
{
return (getName().equals(otherPerson.getName()) && (age == otherPerson.age));
}
public String getName()
{
return name;
}
public void setName(String newName)
{
name = newName;
}
public int getAge()
{
return age;
}
public void setAge(int newAge)
{
age = newAge;
}
}
Student.java Class
public class Student extends Person
{
private String major;
private double gpa;
public Student()
{
super();
major = "Undecided";
gpa = 0.0;
}
public Student(String theName, int theAge, String theMajor, double theGpa)
{
super(theName, theAge);
setMajor(theMajor);
setGpa(theGpa);
}
public String toString()
{
return ("Name: " + getName() + ", Age: " + getAge() + ", Major: " + major + ", GPA: " + gpa);
}
public boolean equals(Student otherStudent)
{
return (major.equals(otherStudent.major) && (gpa == otherStudent.gpa));
}
public String getMajor()
{
return major;
}
public void setMajor(String newMajor)
{
major = newMajor;
}
public double getGpa()
{
return gpa;
}
public void setGpa(double newGpa)
{
gpa = newGpa;
}
}
Family.java Class
public class Family
{
private int famArray = 0;
private Person[] family;
public Family(int size_of_family)
{
famArray = size_of_family;
family = new Person[famArray];
}
public void addPerson(Person p)
{
boolean isPresent = false;
int i;
for(i = 0; i < family.length; i++)
{
if(family[i] != null && family[i].equals(p))
{
isPresent = true;
System.out.println(p.getName() +
" is already present in the family");
}
}
if(isPresent == false)
family[i] = p;
}
public void printOutFamily()
{
for(int i = 0; i < family.length; i++)
{
System.out.println(family[i].toString());
}
}
public static void main(String[] args)
{
Family f = new Family(8);
Person fred= new Person("Fred Flintstone", 50);
System.out.println("created " + fred);
f.addPerson(fred);
f.addPerson(fred);
Student fredStudent = new Student("Fred Flintstone", 50, "Math", 3.1);
System.out.println("created "+ fredStudent);
f.addPerson(fredStudent);
Person wilma = new Person("Wilma Flintstone", 48);
f.addPerson(wilma);
Student george= new Student("George", 21, "Politics", 3.1);
System.out.println("created " + george);
f.addPerson(george);
george.setName("Georgie");
f.addPerson(new Student("George", 21, "Politics", 3.1));
f.addPerson(new Student("John", 18, "Geology", 2.9));
f.addPerson(new Student("Jane", 21, "Music", 3.2));
f.addPerson(new Student("Tarzan", 22, "Gymnastics", 4.0));
f.addPerson(new Student("Jim", 21, "Physics", 2.5));
System.out.println("****** family listing: ");
f.printOutFamily();
}
}
Here's the problem, in Family#addPerson method:
if(isPresent == false)
family[i] = p;
You're adding the element in position i. If the element is not found, then i value will be family.length, thus giving you the exception.
Use int famArray field instead:
if(isPresent == false) {
family[famArray++] = p;
}
Or in an easier way for starters:
if(isPresent == false) {
family[famArray] = p;
famArray = famArray + 1;
}
As an addition to your current problem, you should first check if the famArray element is equals to family.length. If they're the same, then increase the array or do not allow more elements.
You state you have the same problem. This is because you're initializing famArray with the length of the array, noted in Family class constructor:
public Family(int size_of_family) {
famArray = size_of_family; //here
family = new Person[famArray];
}
Change the code to:
public Family(int size_of_family) {
famArray = 0;
family = new Person[size_of_family];
}
And you're done.
The problem is the line
family[i] = p;
This occurs after a for loop which increments i to be equal to the length of the array. I don't have any suggestions to fix it because I'm not sure what you are trying to do here.