Get and Set methods in another classes - java

Im learning java and I have problem with get and set methods in other classes.
My first class is named Department and second is named Company. I would like to set number of staff in class Department and get number of staff in class Company.
Department class
public class Department {
public int staffNumber;
public Department() {
}
public void setStaffNumber(int staff) {
this.staffNumber= staff;
}
}
Company class
public class Company {
public Department staffNumber;
public Company() {
}
public Department getStaffNumber() {
return Department.staffNumber = Department.staffNumber;
}
}
Can you please help me with error message - non-static variable staffNumber cannot be referenced from a static context ?
Thank you

The problem is here:
return Department.staffNumber = Department.staffNumber;
The compiler will read Department.staffNumber as: staffNumber is a static variable in the Department class. There your problem.
In order to solve this, you should just return the instance data:
public Department getStaffNumber() {
//<Department attribute in the class>
return staffNumber;
}
By the way,even if you have a Department.staffNumber static attribute inside the Department class, the proposed line return Department.staffNumber = Department.staffNumber; won't make any sense. It's similar to this:
public class SomeClass {
int x;
public int getX() {
//return x = x; //clumsy
return x; //now this might be better
}
}

You are trying to acces the variable staffNumber as it was a static variable.
If you want to return the staffNumber, you should return staffNumber.staffNumber. You are using bad semantics though...you should have:
public class Company {
public Department m_department;
public Company() {
m_department=new Department();
}
public Department getStaffNumber() {
return m_department.staffNumber;
}
}

public Department getStaffNumber() {
return Department.staffNumber = Department.staffNumber;
}
Department.staffNumber is accessed like a static variable.
It should be return staffNumber.
Your getter normally wouldn't init. It should just return.
If you want to return Department then it should be return staffNumber
If you want to return Department.staffNumber it should be
return staffNumber.staffNumber changing the return type to an int... and fix the variable names!

You seem to be confused about basic concepts.
Do the following
public class Department {
public int staffNumber;
public Department() {
}
public void setStaffNumber(int staff) {
this.staffNumber= staff;
}
public int getStaffNumber() {
return staffNumber;
}
}
Now using StaffNumber in your Company class
public class Company {
public Department dept;
public Company() {
dept= new Department();
}
public int getDepartmentStaffNumber() {
return dept.getStaffNumber();
}
public void setDepartmentStaffNumber(int staff) {
dept.setStaffNumber(staff)
}
}

Related

How to access a private object within a private object in Java?

I am trying to access an object within an object here. Below are the three classes. I simplified this that it makes the same error as in the full program.
This is the main class.
import java.util.Scanner;
public class TestMain
{
public static void main (String[] args)
{
createStudent();
}
public static Student createStudent()
{
Student another = new Student();
another.depart(101,"CS");
return another;
}
}
The second one,
public class Student
{
private int sid;
private String sname;
private Department department;
public int getSid()
{
return sid;
}
public String getSname()
{
return sname;
}
public void depart(int departid, String departname)
{
department.setDid(departid);
department.setDname(departname);
}
public void setSid(int stusid)
{
this.sid = stusid;
}
public void setSname(String stusname)
{
this.sname = stusname;
}
}
The third one,
public class Department
{
private int did;
private String dname;
public int getDid()
{
return did;
}
public String getDname()
{
return dname;
}
public void setDid(int deptdid)
{
this.did = deptdid;
}
public void setDname(String deptdname)
{
this.dname = deptdname;
}
}
No matter what I do, this program returns a run time error,
Exception in thread "main" java.lang.NullPointerException
at Student.depart(Student.java:17)
at TestMain.createStudent(TestMain.java:13)
at TestMain.main(TestMain.java:7)
What is NullPointerException and how to avoid this? Please help me.
The exception is occurring because you did't create the object in the depart method. You can use this:
public void depart(int departid, String departname)
{
department = new Department();
department.setDid(departid);
department.setDname(departname);
}
The problem is that when you create a Student object, you need to initialize each member object i.e. the department object is null, so when you do department.setDid(101), it returns an exception.
To fix this, create a custom constructor for the Student class as so:
Student()
{
department = new Department();
sid = 0;
sname = "";
}
Edit: As Sebastian has rightly pointed out in the comment below, it's actually pretty unnecessary to initialize primitive types in constructors. However, please note that you must do this for String types, as their default value is null, not "", which could cause problems later on.
in your department class in depart method you don't create instance of department and department field is null use this instead:
department = new Department();
public void depart(int departid, String departname){
department = new Department();
department.setDid(departid);
department.setDname(departname);
}

Java code example for read only interface pattern

Consider the following code for a read only interface pattern in Java:
package package2;
public interface AccountsReadOnly {
public String getValue();
}
package package1;
import package2.AccountsReadOnly;
class Accounts implements AccountsReadOnly {
private String name;
public Accounts() {
name = "unknown";
}
public String getValue() {
return name;
}
public void setValue(String name) {
this.name = name;
}
}
package package1;
public class Manager {
Accounts allAccess;
public Manager() {}
}
package package2;
public class Employee {
public AccountsReadOnly accountReadOnly;
public Employee() {}
}
public class Demo {
public static void main(String[] args) {
Manager m = new Manager();
Employee e = new Employee();
Accounts a = new Accounts();
m.allAccess = a;
m.allAccess.setValue("Andrew");
System.out.println(m.allAccess.getValue());
e.accountReadOnly = a;
System.out.println(e.accountReadOnly.getValue());
}
}
I can't understand this line as this is the first time for me to see this format:
m.allAccess.setValue("Andrew");
Is it possible to use instead of this line since they have the same reference?
m.setValue("Andrew");
Is m.allAccess a reference of the object?
Is it possible to use instead of this line since they have the same reference?
no, m.setValue("Andrew"); does not work, because the Manager-class has no function setValue
Is m.allAccess a reference of the object?
yes, allAccess references the Account-object which is set in this line: m.allAccess = a;
The getValue and setValue methods should really be named getNameand setName, because that what they do. setValueshould return a value, e.g. the account's balance.
Also nameis not read-only if you have a setter for it.

Declaring a nested class in Java

I'm a bit confused with subclasses.
Here's my code:
public class MedHistory {
private String grafts;
private String allergies;
private String diseases;
private String surgeries;
private String medicalTreatment;
//Constructors (#2)
public MedHistory(String allergies, String diseases, String grafts,
String treatments, String surgeries) {
this.allergies=allergies;
this.diseases=diseases;
this.grafts=grafts;
this.medicalTreatment=treatments;
this.surgeries=surgeries;
}
public MedHistory() {
this.allergies="";
this.diseases="";
this.grafts="";
this.medicalTreatment="";
this.surgeries="";
}
//Getters
public String getGrafts() {
return grafts;
}
public String getAllergies() {
return allergies;
}
public String getDiseases() {
return diseases;
}
public String getSurgeries() {
return surgeries;
}
public String getMedicalTreatment() {
return medicalTreatment;
}
//Setters
public void setGrafts(String grafts) {
this.grafts = grafts;
}
public void setAllergies(String allergies) {
this.allergies = allergies;
}
public void setDiseases(String diseases) {
this.diseases = diseases;
}
public void setSurgeries(String surgeries) {
this.surgeries = surgeries;
}
public void setMedicalTreatment(String medicalTreatment) {
this.medicalTreatment = medicalTreatment;
}
public class FemMedHistory extends MedHistory {
private List<Birth> births = new ArrayList<Birth>();
//Constructors (#2)
public FemMedHistory(String allergies, String diseases, String grafts,String treatments, String surgeries, List<Birth> birthlist) {
super(allergies,allergies,grafts,treatments,surgeries);
this.births=birthlist;
}
public FemMedHistory() {
super();
this.births=null;
}
//Getter
public List<Birth> getBirths() {
return this.births;
}
//Setter
public void setBirths(List<Birth> list) {
this.births=list;
}
}
}
When I try to create an new FemMedHistory object like this:
List<Birth> list = new ArrayList<Birth>();
list.add(new Birth(new GregorianCalendar(2011,4,10),"kaisariki",4));
FemMedHistory female = new FemMedHistory("allergia2","astheneia2","emvolia2","farmekeutiki agwgi2", "xeirourgeia2", list);
I get the error:
No enclosing instance of type MedHistory is accessible. Must qualify
the allocation with an enclosing instance of type MedHistory (e.g.
x.new A() where x is an instance of MedHistory).
So, which is the right way to use a subclass?
When you declare a nested class it only available through the Outer class.
To access it outside, you will need to either make the FemMedHistory class static.
public static class FemMedHistory extends MedHistory {...}
access it through the MedHistory class
MedHistory.FemMedHistory myMedHistory = ...
or declare it in it's own Java file.
You have declared your subclass as an inner class, which means that you can't create an instance of it without first creating an instance of the containing class.
The most common way to solve this is to declare it as a separate class, which would get rid of your error.
Long story short: cut all the FemMedHistory code and paste it into FemMedHistory.java. The way it is now you have involved Java concepts which you have not yet mastered. Also, that class really does belong in a separate file.

Polymorphism - Call Base class function

Is it possible to call base class function without modifying both base and derived classes?
class Employee {
public String getName() {
return "Employee";
}
public int getSalary() {
return 5000;
}
}
class Manager extends Employee {
public int getBonus() {
return 1000;
}
public int getSalary() {
return 6000;
}
}
class Test {
public static void main(String[] args) {
Employee em = new Manager();
System.out.println(em.getName());
// System.out.println(em.getBonus());
System.out.println(((Manager) em).getBonus());
System.out.println(em.getSalary());
}
}
Output:
Employee
1000
6000
How shall I call the Employee's getSalary() method on em object?
You can't. You could add a method like this to Manager if you wanted:
public int getEmployeeSalary()
{
return super.getSalary();
}
Use an Employee object instead:
Employee em = new Employee();
You can call the superclass's method from within the subclass.
class Manager extends Employee {
public int getBonus() {
return 1000;
}
public int getSalary() {
return super.getSalary();
}
}

Struts 2 does not populate POJO from client

I have a Java Object with many other nested Objects and lists of Objects. When the request arrives from the client, I see that the Object is populated only to a few levels. Is there any configuration that sets this is Struts 2? Here is my example.
class MyActionClass extends ActionSupport {
private Abc abc;
public Abc getAbc() {
return abc;
}
public void setAbc(Abc abc) {
this.abc = abc;
}
public String populate() {
MyService myService = new MyService();
abc = myService.getMyAbc();
return SUCCESS;
}
public String update() {
MyService myService = new MyService();
myService.updateAbc(abc);
return SUCCESS;
}
}
class Abc {
private List<Def> defList;
private Ghi ghi;
public void setDefList(List<Def> defList) {
this.defList = defList;
}
public List<Def> getDefList(){
return defList;
}
public void setGhi(Ghi ghi) {
this.ghi = ghi;
}
public Ghi getGhi() {
return ghi;
}
}
class Def {
private String name;
private long id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
class Ghi {
private List<Def> defList;
private String ghiName;
public void setDefList(List<Def> defList) {
this.defList = defList;
}
public List<Def> getDefList() {
return defList;
}
public void setGhiName(String ghiName) {
this.ghiName = ghiName;
}
public String getGhiName() {
return ghiName;
}
}
When I call the populate method and when send to the jsp, the iteration happens good with all the elements. But, when I try to update, i.e. when then form is submitted, the update() method is called, but the instance variable abc does not get populated completely.
I have seen the url which is passed and everything seems to be fine. Let me tell you what happens. The url will be something like (splitting with line break for easy understanding here),
&abc.defList[0].name=alex
&abc.defList[0].id=1
&abc.defList[1].name=bobby
&abc.defList[1].id=2
&abc.ghi.ghiName=GHINAME
&abc.ghi.defList[0].name=Jack
&abc.ghi.defList[0].id=1
&abc.ghi.defList[1].name=Jill
&abc.ghi.defList[1].id=2
In this case, the defList inside abc and ghi.ghiName in abc are populated with no issues. But the defList of abc.ghi is not populated. Is this a common behavior of Struts 2? Is ther any means by which this can be overridden?
Got the issue solved. Struts 2 rock. Since the code I got was for a bug fix, did not know what was inside it, not even checked it once.
The culprit was the toString() method which was overridden. This had no check on the map for null and called the entrySet() method on it. This generated Exception and prevented Struts from populating the objects.
For better understanding, Struts do call the toString() method for some purpose while populating. If anyone faces this in future, do remember to check if you have overridden toString() and if everything is set inside it.

Categories

Resources