How to access a private object within a private object in Java? - 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);
}

Related

Java Encapsulation Constructor Method

Hi all I am working on a java code for student health. what I am trying do is
A) Make a constructor method that initializes only the first 2 data fields
(name and date-of-birth). Also, increment the patient counter data field.
B) Secondly make a constructor method that initializes all the data fields. Also, increment the patient counter data field.
If I recall correctly in order to make a constructor method that initializes the first two variables (in this case name and DOB) it goes something like this.
public emr (String name, Long dob){
However when I put that in my emr class my main method comes up with errors saying "constructor emr class cannot be applied to given types"
In my main Method I have
package studenthealthservices;
public class Studenthealthservices {
public static void main(String[] args) {
emr p1 = new emr();
p1.setName("Colin");
emr p2 = new emr();
p2.setName("Anquan");
emr p3 = new emr();
p3.setName("Buster");
emr p4 = new emr();
p4.setName("Hunter");
emr p5 = new emr();
p5.setName("Nori");
}
}
This is my emr class code
package studenthealthservices;
public class emr {
private String name;
private Long dob;
private String rfv;
private double bodyt;
private double hr;
private String diag;
private String pmeds;
public void setName(String name) {
this.name = name;
}
public Long getDob() {
return dob;
}
public void setDob(Long dob) {
this.dob = dob;
}
public String getRfv() {
return rfv;
}
public void setRfv(String rfv) {
this.rfv = rfv;
}
public double getBodyt() {
return bodyt;
}
public void setBodyt(double bodyt) {
this.bodyt = bodyt;
}
public double getHr() {
return hr;
}
public void setHr(double hr) {
this.hr = hr;
}
public String getDiag() {
return diag;
}
public void setDiag(String diag) {
this.diag = diag;
}
public String getPmeds() {
return pmeds;
}
public void setPmeds(String pmeds) {
this.pmeds = pmeds;
}
}
If you do not write a constructor, a public constructor with no arguments is created by default.
This default constructor is the constructor you are using in main when you write new emr().
However, when you write your own constructor, then the default constructor will not be created, so main will no longer compile. If you want main to continue to compile even after you have written the new constructor, you will have to also write a second constructor with no arguments.

Passing a variable from parent to child class in Java

I am completely new to Java... :(
I need to pass a variable from a parent class to a child class, but I don't know how to do that.
The variable is located in a method in the parent class and I want to use it in one of the methods of the child class.
How is this done?
public class CSVData {
private static final String FILE_PATH="D:\\eclipse\\250.csv";
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
}
}
and then the other class
public class UserClassExperimental3 extends CSVData {
public static void userSignup() throws InterruptedException {
//some code here
String firstname= firstname1; //and here it doesnt work
}
}
Actually I think I succeeded doing that this way:
added the variable here:
public static void userSignup(String firstname1)
then used it here:
String firstname=firstname1;
System.out.println(firstname);
But now I can't pass it to the method that needs it.
The variable firstname1 is a local variable. You can't access it outside its scope - the method.
What you can do is pass a copy of the reference to your subclass.
Since you're calling a static method, the easiest way is to pass the reference as an argument to the method call:
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3.userSignup( firstName1 );
}
public class UserClassExperimental3 extends CSVData {
public static void userSignup( String firstNameArg ) throws InterruptedException {
//some code here
String firstname = firstnameArg; // Now it works
}
}
That said, since you're using inheritance, you might find it useful to use an instance method. Remove "static" from the method. In main(), construct an instance of the class, provide it the name, and call the method on the instance.
#Test
public static void main() throws IOException {
//some code here
String firstname1 = array.get(2).get(1);
UserClassExperimental3 instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
}
public class UserClassExperimental3 extends CSVData {
private String m_firstName;
public UserClassExperimental3( String firstName ) {
m_firstName = firstName;
}
public void userSignup() throws InterruptedException {
//some code here
String firstname = m_firstname; // Now it works
}
}
If you also add userSignup() to the CSVData class, you can refer to the specific subclass only on creation. This makes it easier to switch the implementation, and it makes it easier to write code that works regardless of which subclass you're using.
String firstname1 = array.get(2).get(1);
CSVData instance = new UserClassExperimental3( firstName1 );
instance.userSignup();
public class Main {
public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setName("user");
user.setEmail("user#email.com");
user.save();
}
}
public class User extends Model {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import java.lang.reflect.Field;
public class Model {
public void save(){
for(Field field: Model.this.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
System.out.println(field.getName()+"="+field.get(Model.this));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return;
}
}

How to pass an array of objects to a button?

I have two classes: one called Student and the other one called Course. I would like to make a simulation for a simple registration system.
My Student class part has the following form:
class Student
{
private String id,
private Course[] listOfCourses;
private int numCourse;
//accesing methods
public registration(Course course){
listOfCourses[numCourse]=course;
numCourse++;
}
public Course[] getCourse(){
return listOfCourses;
}
}
and the Course class has the following form:
class Course
{
String id, String courseName;
//constructor
//accesing methods
}
I would like that by pressing a buttom in a form made in Java Swing, to display the contents of the courses registered by one specific student into a jTable. I have tried the following, but with no results at all:
Student e=new Student();
Course d[]=new Course[4];
d=e.getCourses(); //to receive the array of Courses from the Student class
for (int i=0;i<d.length;i++){
jTable2.setValueAt(estLista[i].getName(), i, 0);
}
how I can do that? I mean there is a way in which I could get the contents of the array, that is stored in the Course class, into the ActionEvent of the button?
From the code you have provided I believe there atleast one reason why you are not getting the courses.. because it is not set in registration process:) (Also the syntax is not correct unless you have a registration class?) This might not be a complete solution but it corrects one of the problem
public void registration(Course course){
// listOfCourses[numCourse];
listOfCourses[numCourse]=course;
numCourse++;
}
Ok, it is not too clear for me yet, but I will put some code and tell me if it helps you.
Note: Not tested
For Student (sorry I prefer to use lists instead of arrays):
public class Student {
private String id;
private List<Course> takenCourses;
public void registration(Course course){
if (this.takenCourses != null) {
takenCourses.add(course);
} else {
System.err.println("an array has not been specified.");
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Course> getTakenCourses() {
return takenCourses;
}
public void setTakenCourses(List<Course> takenCourses) {
this.takenCourses = takenCourses;
}
For course:
public class Course {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
For your UI, I just created a "simulation" of UI, I assume you have implemented something more complete... I assume you have intialized the components as global variables for your frame or panel or at least you have methods to get them.
public class UIHelper extends JFrame {
Student student = new Student();
JButton btnAction;
JTable myTable;
public UIHelper() {
//Methods for creating UI
//.
//.
//.
student.setId("stackoverflowed");
student.setTakenCourses(new ArrayList<Course>());
btnAction = new JButton("Action!");
//Methods of the JButton (...)
btnAction.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Now just process since student is a global variable (you can set it static as well) but it shouldn't be a good practice at all
for (Course course : student.getTakenCourses()) {
System.out.println(course.getName());
//Add the element to your table.
}
}
});
}
public static void main(String[] args) {
//Assume this is your UI
new UIHelper();
}
Hope I give you an idea, best regards.

Conflict between passing an Array from Main Class to Function, but also wanting to use return vales from my "getter" method

In my main class, I have a static method which I pass the array into. It is a static method because if I want to pass something from the main class body to this method, it must be static. In a separate class I have a series of getters and setters (which must be non static ).
How can I pass my static array in and use the non-static getters and setters?
EDIT- In the arraySearch method...I cannot pass in the Person Array and access the getters in the Person Class
public class Main {
public static void main(String[] args) {
Person One = new Person("Alice","Foo", 22, false);
Person Two = new Person("Alice", "Foo",22, false);
Person Three = new Person("Bob","Bar",99, false);
Person Four = new Person("Joe","Blogs",64, false);
Person Five = new Person("Jane", "Joe",42, false);
Person [] People = {One,Two,Three,Four,Five};
printArray(People);
}
public static void printArray(Person [] People)
{
for(int i=0;i<People.length;i++)
{
System.out.println(People[i]);
}
}
public void arraySearch(Person [] People)
{
for(int i=0;i<People.length;i++) //Searches the Array of Objects
{
String firstName = Person.getFirstName();
String secondName=Person.getSecondName();
if((firstName.equals("Joe")&&secondName.equals("B" + //Searches for Joe Blogs and Jane Joe
"logs"))|| ((firstName.equals("Ja" +
"ne")&&secondName.equals("Joe"))))
{
int age=Person.getAge();
Person.setAge(age+1); //Increments Age by 1
}
}
}
}
public class Person {
private String mfirstName;
private String msecondName;
private int mage;
private boolean misRetired;
public Person(String firstName,String secondName,int age, boolean isRetired)
{
mfirstName=firstName;
msecondName=secondName;
mage=age;
misRetired=isRetired;
}
//GETTERS
public String getFirstName()
{
return mfirstName;
}
public String getSecondName()
{
return msecondName;
}
public int getAge()
{
return mage;
}
public boolean getRetired()
{
return misRetired;
}
//SETTERS
public void setFirstName(String firstName)
{
mfirstName=firstName;
}
public void setSecondName(String secondName)
{
msecondName=secondName;
}
public void setAge(int age)
{
mage=age;
}
public void setRetired(boolean isRetired)
{
misRetired=isRetired;
}
//STRING
public String toString()
{
return (mfirstName+"-"+msecondName+"-"+mage+"-"+misRetired);
}
}
This is very basic Java question. You need to create instance of object containing setter/getters from your static method. You can also pass static array in setter of this object. Then you should be able to call those getter/setter methods.
public class Main
{
public static void main(String[] args)
{
MyClass myclass = new MyClass();
myclass.setArgs(args);
System.out.println(myclass.getArgs());
}
}
public class MyClass
{
private String[] args;
public String[] getArgs()
{
return args;
}
public void setArgs(String[] args)
{
this.args= args;
}
}
You have to create an object instance from the class with the getters.
The Amit answer is correct; this just has some more info and more closely matches the situation you describe in your question.
Your basic premise "It is a static method because if I want to pass something from the main class body to this method, it must be static." is wrong. The method to which you pass the array does not need to be static. Here is some code:
public final class Main
{
private static final String[] staticOTron =
{
"one",
"two",
"three"
};
public static void main(final String[] args)
{
String[] hootBerrySause;
Tool tool = new Tool();
tool.setStaticOTron(staticOTron);
hootBerrySause = tool.getStaticOTron();
for (String value : hootBerrySause)
{
System.out.println("Value: " + value);
}
}
}
// this can be in a different file.
public final class Tool
{
private static String[] staticOTron;
public void setStaticOTron(final String[] newValue)
{
staticOTron = newValue;
}
public String[] getStaticOTron()
{
return staticOTron;
}
}
Sunil kumar from vmoksha
Your asking deeper navigation
Just create the instance of particular or create the getter &and setter in the main
class

Get and Set methods in another classes

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)
}
}

Categories

Resources