Java Encapsulation Constructor Method - java

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.

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.

JUnit test for getter method of custom object type

I need to write unit tests for my methods. I'm having a bit of trouble because I'm new to JUnit. I need to write a test for a getter method of an object type I created. The object type is UnitInfo, and I need to write a test for the method
#Override
public UnitInfo getInfo() {
return info;
}
in the class building. I put my building class, UnitInfo class and my buildingTest class in the code below. Any help is appreciated.
package main.model.facility;
import java.util.List;
public class UnitInfo {
private int capacity;
private String name;
private int idNumber;
private List<String> details;
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public List<String> getDetails() {
return details;
}
public void setDetails(List<String> details) {
this.details = details;
}
public void addDetail(String detail) {
details.add(detail);
}
public void removeDetail(String detail) {
details.remove(detail);
}
}
Building class:
package main.model.facility;
import java.util.List;
public class Building extends Facility {
private List<IFacility<UnitInfo>> subunits;
private UnitInfo info;
private ScheduleManager schedule;
#Override
public UnitInfo getInfo() {
return info;
}
#Override
public ScheduleManager getScheduleManager() {
return schedule;
}
#Override
public List<IFacility<UnitInfo>> listFacilities() {
return subunits;
}
#Override
public int requestAvailableCapacity() {
int availableCapacity = 0;
for (IFacility<UnitInfo> subunit : subunits){
availableCapacity += subunit.requestAvailableCapacity();
}
return availableCapacity;
}
}
Junit
public class BuildingTest {
Building defaultBuilding = new Building();
ScheduleManager defaultSchedule = new ScheduleManager();
#Before
public void setUp() throws Exception {
}
#After
public void tearDown() throws Exception {
}
#Test
public void testGetInfo() { //this is the test I need to write
Building b = defaultBuilding;
assertEquals(b.getInfo(), null);
}
#Test
public void testGetScheduleManager() {
Building a = defaultBuilding;
assertEquals(a.getScheduleManager(), null);
}
Don't build your Building at the class level, create it inside the unit test so that each test has its own Building to work with. This way they won't interfere with each other.
Your test seems fine at the moment, you don't initialize info when you construct a new Building so info is null, and you are asserting that in your unit test. You could also use assertNull(b.getInfo());.
#Test
public void testGetInfo() { //this is the test I need to write
Building b = new Building()
assertEquals(b.getInfo(), null);
}
If you did initialize info to something else, say info = new UnitInfo(), then you could change your test to:
#Test
public void testGetInfo() { //this is the test I need to write
Building b = new Building()
assertNotNull(b.getInfo());
}
How about if, when you create a new Building you initialized info and set some of the fields.
info = new UnitInfo();
info.setIdNumber(100);
info.setName("Some Unit Info");
Then in your unit test you could assert that the fields were set:
#Test
public void testGetInfo() { //this is the test I need to write
Building b = new Building()
assertNotNull(b.getInfo());
assertEquals(b.getInfo().getIdNumber(), 100);
assertEquals(b.getInfo().getName(), "Some Unit Info");
}
The idea with unit tests is to exercise your code; call your methods and then assert that the results are what you expect. Once you have a good base of unit tests against all your code, you can feel confident about modifying it because you know that your tests will tell you when you break something.
Keep your tests small and simple, don't do too much. Just do your setup, call a method and make sure the results are correct. Then write a new test, and do something else. Don't write tests that do 5 different things.

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.

Categories

Resources