Fields / Getter And Setter Methods And Constructors
Mar 12, 2015
A blood clinic has hired a team of software developers to build a custom application to track patients. The clinic needs to keep a record of each patient and his or her blood data. Ultimately, they want all of the information stored in a database. As a starting point, the development team leader informs the team that the application has to have a set of core classes that represent the “real-world” entities the program needs to deal with. As a developer on the team, your job is to build a Patient class along with a BloodData class so that each Patient contains a BloodData object. This principle is known as “composition.”
Building the Framework Begin by creating a public Java class named PatientBuilder that contains a main method. Then, in the same file, create a non-public class named Patient and another named BloodType. Save the file as PatientBuilder.java. Note: If this was a real development project, you would put each class into it’s own file and put the files in the same folder. By combining them all into one file, we avoid having to submit three separate files, making it easier to keep all your work in one place.The BloodData Class This class should hold all of the attributes to hold the data the clinic needs for a given patient’s blood. Implement the following capabilities to accomplish this objective:
• Create a field to hold a blood type. The four possible blood types are O, A,B, and AB. For this project, you can simply define the field as a String.
• Create a field to hold the Rh factor. The two possible Rh factors are + and –.For this project, you can simply define the field as a String.
• Create getter and setter methods for both fields.
• Create a default constructor that sets the fields to “O” and “+”
• Create an overloaded constructor that accepts two parameters – one for a proposed blood type, and another for a proposed Rh. The constructor
should call the set methods and pass these parameter variables in to them.The Patient Class This class should hold all of the attributes to hold the data the clinic needs for a given patient’s blood. Implement the following capabilities to accomplish this objective:
• Create a field to hold an ID number along with get and set methods.
• Create a field to hold the patient’s age along with get and set methods.
• Create a field to hold the BloodData for a Patient. When declaring the field, initialize it by instantiating a BloodData object. Create get and set methods.
• Create a default constructor that sets the ID to “0”, age to 0, blood type of the BloodData object to “O”, and Rh value of the BloodData object to “+”.
• Create an overloaded constructor that accepts the following parameters: ID,age, blood type, and Rh. The constructor should call the set methods for the field associated with each parameter.The PatientBuilder Class.This class should contain the main method from which the program runs. In that method, implement the following functionality:• Ask the user for the ID, age, blood type, and Rh factor of a Patient.
• Create a Patient object, passing all of the data obtained from the user into the object.
• Write the code necessary to display the ID, age, blood type, and Rh factor of the Patient by calling the appropriate get methods of the object.
MY CODE ( which does not compile since it is wrong...)
import java.util.Scanner;
public class PatientBuilder
{
public static void main(String[] args){
String patientID;
int patientAge;
String patientRh;
String patientBlood;
[code].....
View Replies
ADVERTISEMENT
Jul 22, 2014
Write a class Month that represents one of the twelve months of the year. It should have three attributes for
the name of the month,
the number of days in the month, and
the birthstone.
Also add constructors and getter/setter methods to access the attributes.
You may use the following code to test your class.
Java Code:
import java.util.*;
public class Month
{
// ADD CODE HERE!!!
public static void main(String[] args)
{
Month[] months = new Month[12];
[Code] ....
So what I have added so far is (under public class month { :)
Java Code:
String monthName, monthBirthStone;
int monthDays;
public Month (String name, int days, String birthstone)
{
monthName = name;
monthBirthStone=birthstone;
monthDays=days;
} mh_sh_highlight_all('java');
So I believe that is the constructor. I still do not understand several things:
What would I need the getter and setter for?
I tested it using just the above code, and using month 1 I got:
Month@5a1cfb56
This makes sense as I obviously didn't do anything in order to get it in a String format for the array. But I do not understand this still - how would I get the constructor to output a string (to then be in the array?)
View Replies
View Related
Apr 15, 2015
i need to change my code in order to stop the member variables from being directly altered and its been suggested that i should use a setter and getter method. Ive read up about these and im still unsure at how they should be implemented into my code for my project.
import ddf.minim.*;
DragShape[] piece =new DragShape[77];
PImage puz16;
PImage frame;
PImage text;
[code]....
View Replies
View Related
Jan 3, 2015
I have been assigned with a task to have a class which has the methods setImage and getImage. These methods are meant to set the ImageIcon by using the url taken from another class and the getImage method is meant to return the ImageIcon that was set before hand. The problem is that i'm not really familiar with ImageIcon so the code in both my methods is giving out errors and i just can't figure out why. Heres the code in the class that has the setImage and getImage methods:
public class Die implements DieInterface {
private ImageIcon [] image = new ImageIcon[6]; //the number of images that would be stored in this array is 6 (six faces of the dice)
ublic Die()
{
//This puts images into the images array(the different die faces)
image = new ImageIcon[6];
[code]....
And this is where i call the methods (set and get methods) in the other class:
die1.setImage(new ImageIcon(Dice.class.getResource("face1.png")));
die1.getImage();
View Replies
View Related
May 8, 2014
I am trying to set my setter and getter various times o that I can store a name, price and value but i can only set it once. Once i try to set again the previous entry resets.I have tried
job = sc.next();
jobdetails.setjob(job);
wage = sc.next();
wageD.setwage(wage);
hours = sc.next();
hourd.sethour(hour);
This sets the values for me and i receive the input i entered but if i try to enter again the input from before is removed.I have searched array lists and tried
[code] List<Object> list new ArrayList<Object>();
list.add(jobname)
list.add(price)
list.add(Event)
out.println(list.get(0));
for (Object s : list) {
out.println(s);
}
For this to work I would have to keep adding list.add. Is there a way I can use the array to add a new item to the list so that when I try to display what I have stored in the setter and getter it will display what I have entered in each time instead of only the last input? or any other way that may be possible to do this?
View Replies
View Related
Feb 18, 2014
Class UserAssessBean{
private String username;
private int userid;
private ArrayList<ModuleBean> module;
--{get/set}--
[Code] ....
How can i access the getters/setters of module bean, when it was returned as array list in UserAssessBean?
View Replies
View Related
Feb 24, 2012
i'm trying to modify and use a GUI to set the variables the setter methods. while the code seems valid to me and should work perfectly, i get ArrayIndexOutOfBounds and StringIndexOutOfBounds and respectively lines 111 and 134. i'm am not the original author of this code, all i want is to get it to work fine.
1package de.kugihan.dictionaryformids.dictdconv;
2
3import java.io.FileOutputStream;
4import java.io.IOException;
5import java.io.OutputStreamWriter;
6
[code]....
View Replies
View Related
Mar 23, 2015
If i have a class(lets say class name is Approval) with the following private members: String recip_id, Int accStat, String pDesc, String startDate How can i create public get and setter methods for these private members of the class?
View Replies
View Related
Dec 10, 2014
This program is basically complete. It compiles and runs. It is a college course assignment that I pretty much completed but for the last part in which I'm suppose to change the values of all fields and display the modified values using a toString method. Modifying the values of the fields is where I am stuck. I don't think I need to create a new text data file to do this. The instructor only asked that all the values of fields be changed and this was the last part of the assignment so I don't think it involves creating additional ObjectOutputStream and ObjectInputStream objects. I'm getting a NullPointerException error on line 161.Here is the code. I'm also including the input data file.
//create program so that objects of class can be serialized, implements interface Serialiable
//create constructor with 4 parameters with accompanying get and set methods, Override toString method
//create text file with 5 records, create Scanner object,ObjectOutputStream, and ObjectInputStream
//create new ItemRecord object, change values of all fields in ItemRecord object using object's set methods
//modify ItemRecord object using toString method
[hightlight =Java]import java.io.Serializable;
public class ItemRecord implements Serializable
[Code] .....
This is the error message:
----jGRASP exec: java ItemRecordReport
Item Cost Quantity Description
Number
A100 $ 99.99 10 Canon PowerShot-135
A200 $149.99 50 Panasonic-Lumix T55
A300 $349.99 20 Nikon- D3200 DSRL
A400 $280.99 30 Sony- DSC-W800
A500 $ 97.99 20 Samsung- WB35F
Exception in thread "main" java.lang.NullPointerException
at ItemRecordReport.main(ItemRecordReport.java:161)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Here is the data file:
A100 99.99 10 Canon PowerShot-135
A200 149.99 50 Panasonic-Lumix T55
A300 349.99 20 Nikon- D3200 DSRL
A400 280.99 30 Sony- DSC-W800
A500 97.99 20 Samsung- WB35F
Here is the data file for the modified field values.
B100 98.00 10 ABC1010
B200 97.00 15 DEF1020
B300 96.00 10 GHI1030
B400 95.00 05 JKL1040
B500 94.00 01 MNO1050
View Replies
View Related
Dec 7, 2014
how to differ between fields that are not exists to fields that are null? because in my api when someone wants to delete a field he sends null instead of a value. and if he doesnt want to effect this feild he doesnt send it.
{
"a" : {"1","2"},
"b" : "hello"
}
{
"a" : null,
"b" : "hello"
}
{
"b" : "hello"
}
View Replies
View Related
Jul 2, 2014
I have question on best practice on declaring variable and using getter. Is there any performance issue if I used getter every time to access the properties values or Is better to use getter once, store in variable then use that variable whenever needed.
a) What is the best practice?
b) Also what if getter in deep level e.g. myTopObj.getInnerOne().getInnerTwo().getProp();
Option 1
Java Code:
var myProp = obj.getProp();
x = myProp;
y = myProp mh_sh_highlight_all('java');
Option 2
Java Code: x = obj.getProp();
y = obj.getProp(); mh_sh_highlight_all('java');
View Replies
View Related
Sep 16, 2014
I have 2 classes. TestClassA has 1 getter and 1 setter. From my second class, TestClassB, I want to access the getter method of TestClassA. If I try to access it, I get null. How do I do it?I do not want the methods to be declared as static. How can the getter method value be printed in TestClassB (without marking anything as static)?
public class TestA {
private String name;
public String getName() {
return name;
[code]....
View Replies
View Related
Aug 28, 2014
so here's my code
import java.io.*;
public class Movies {
public String title;
public String director;
public String theme;
public Title(String title)
[code]....
the error is in line 9 which is
public Title(String title)
and the error is (error: invalid method declaration; return type required)
View Replies
View Related
Sep 15, 2014
I'm working on this program for a class to create objects of a commissioned employee and union employee. Everything seems to work ok, but when I run my final pay calculation, one of my getter functions will not pass the variable for the pay into a class specific variable called check. here is the code in this function.
public void finalPayCal_U() {
setweekPay();//calculates weeks pay under 40 hours, stored in getweekpay
check = getweekPay();
if(getHours() > 40){
check = check + (1.5 * (getHours() - 40) * getRateOfPay());
}
check =- Dues;
}
}
The issue lies in check = getweekPay();
I thought this was a legal move, but I can't get it to work. It doesn't come back with anything more than 0 any time I run it.
All of these functions are out of the base class, employee (this function itself lives in the derived union class)
public void setweekPay() {
if (hours <= 40) {
weekPay = hours * rateOfPay;
} else {
weekPay = 40 * rateOfPay;
}
}
When I run, this function works as it returns the value when i print it to test.
however, when I do the part that says check = getWeekPay() above, it doesn't change the check variable. The only thing I have on the check variable is the dues taken out of it at the end, so it ends up being a negative number.
I have a similar problem with the other derived class's check variable. Both classes have the same variable as private but one is check the other checkC.
View Replies
View Related
Nov 24, 2014
I have a PrimeFaces page with a calendar component on it. Radio buttons on that page work fine and call the setter method on the back end. The Calendar however doesn't call the setter. The getter method is called on page display.I'm using the PrimeFaces v 5.0 jar file.
<h:panelGrid columns="4" cellspacing="5">
<p:radioButton id="timeframeOpt10" for="searchTimeframe" itemIndex="10" style="padding-left:30px;"
onchange="document.getElementById('_listenerportlet_WAR_listenerportlet_:articleSearchForm:tabView:timeframeChecked').innerHTML = '(#{i18n['timeframe-specify-dates-label']})';" />
<h:outputLabel value="#{i18n['timeframe-specify-dates-label']}" style="padding-left:10px;" />
<h:panelGrid columns="2" style="align-content:center;">
<p:outputLabel value="#{i18n['timeframe-dates-start-label']}" />
<h:outputText value=" " />
<p:calendar value="#{articleSearchFormBean.timeframeStart}" showOn="button" />
</h:panelGrid>
<h:panelGrid columns="2">
[code].....
View Replies
View Related
Sep 21, 2014
I hope I'm putting this question in the right folder. I have an array of objects, and I have defined a setter for a variable in the object. When I call the setter, I get a NullPointerException. Here is the relevant code for the object.
public class Digit extends Thread {
private int digit;
public void setDigit(int digit) {
this.digit = digit;
}
// run method follows
}
Here is the portion of the main class where I define an array and then call the setter.
Digit[] digits = new Digit[10];
for (int i = 0; i < digits.length; i++) {
digits[i].setDigit(i); // NullPointerException occurs here
}
View Replies
View Related
Apr 6, 2014
Can you give me a simple description of what overloading a constructer is?
View Replies
View Related
Sep 1, 2014
Can i use constructors in an interface?
interface AI {
public abstract AI();
public abstract void hello();
}
Output:
I got the error as the method AI() should have return type.
View Replies
View Related
Jun 3, 2014
Is it possible to combine two classes that I have defined to contain some of the same elements so that NetBeans stops giving me errors? I don't want to get rid of any necessary code, and if both classes are necessary, should I just rename one of them? One class is an ArrayList that I am using to write the information for employees entered to a text file "employee.txt." I also want users to be able to call on this information via employeeID in order to display employee information. The code is the following:
public ArrayList<Employee> getEmployees() {
// if the employees file has already been read, don't read it again
if (employees != null)
return employees;
employees = new ArrayList<>();
if (Files.exists(employeesPath)) // prevent the FileNotFoundException {
[code]....
The other class is a getEmployee class that I previously defined before attempting to read the information from the text file and display it in the console. It is as follows:
private void getEmployees() {
try {
// if the file doesn't exists, create it
if (!Files.exists(employeesPath))
Files.createFile(employeesPath);
BufferedReader in =
new BufferedReader(
new FileReader(employeesFile));
[code]....
View Replies
View Related
Feb 9, 2014
I remember reading that a super() call to parent no-argument constructor is automatically inserted by compiler. So, if i have a chained hierarchy of classes (starting at top, with Object), will there be a chain of super() calls, going from bottom to top in the chain ? Will a super() call be inserted in child, if i provide a no-argument constructor for this class ?
View Replies
View Related
Nov 19, 2014
I am getting error in second constructor that I have created, it gives an error: cannot find symbol variable
package Objects;
import javax.swing.JOptionPane;
public class Constructor {
public static void main(String[] args) {
Piggybank1 pg1 = new Piggybank1("Abhinav", 500);
pg1.deposit(200);
pg1.withdraw(10);
[Code] ....
View Replies
View Related
Mar 20, 2014
We are learning about how to pass objects into constructors. In our class, we made this following code:
public class InventoryItem {
//fields
private String description;
private int units;
//Add New constructor
public InventoryItem(InventoryItem some_object) {
description=some_object.description;
[Code] .....
As you can see the object of the same class is passed as the argument. Inside the constructor, our teacher did
some_object.description
This constructor, from my understanding, copies the description field and unit field to an object to the new object of class. Meanwhile, here is the demo class.
public static void main(String[] args)
{
//Create object
InventoryItem item1;
item1=new InventoryItem("hammer",20);
System.out.println("Item 1: ");
[Code] .....
Over here, my teacher uses :
.getDescription
My problem is that in the constructor of the first class I showed, why didn't he use
.getDescription
method instead of this
.description
May I know what is difference between these two. If I use .getdescription that would return the value of a field from that object too.
View Replies
View Related
May 26, 2014
So while experimenting with constructors, repeating constructors with the same parameters, and with different parameters. I got an output -explaining how I got it.
I made 2 classes. a "support class" (has all the info) and an "execute class" (executes info).
Support:
package inschool;
public class Constructors {
String video;
public Constructors() {
video = "frozen";
[Code] ....
Execute:
package inschool;
//this is part of Constructors class
public class App{
public static void main(String[] args){
[Code] ....
The Output:
the video name is frozen
Second constructor running
Constructor running!
the video name is frozen
Output Explanation:
constructor call number 1 and 3 are the same (essentially) and both refer to the same constructor.
My Question: if both call #1 and #3 refer to the same constructor, why is the output for #1 "the video name is frozen"
while the output for #3 used both methods in the accessed constructor-with the resulting output as
"Constructor running!"
and
"the video name is frozen"
I double checked the output-and this time made sure to scroll up ... its the same result
View Replies
View Related
Apr 4, 2014
I have a class named Cash shown below
public class Cash
{
//Quanity Field and RetailItem Object field
private int total_units;
private Retail myRetail;
//Create first constructors
public Cash()
{
this(0,null);
[Code] ....
I'm seriously need to understand the concept of making shallow copies and deep copies. My book has shown me that its better to perform deep copies and I have followed that method. if you guys look in my constructor of the cash class
//Create a a constructor
public Cash(int total_units,Retail myRetail)
{
this.total_units=total_units;
this.myRetail=new Retail(myRetail);
Apparently I have field in Cash Class named
Retail myRetail
When I pass in an argument from my demo, I'm making a copy of that object from the demo class. In my retail class, I have the following copy constructor .
//Make a copy constructor
public Retail(Retail Object1)
{
Item_Name=Object1.Item_Name;
Item_Number=Object1.Item_Number;
// if I use this then my program would work//this.cost=Object1.cost;
//if I use this part of code below, my program won't work at all and I would get an error saying Exception in thread "main" java.lang.NullPointerException
this.cost.Item_Cost=Object1.cost.Item_Cost;
this.cost.Wholesale_Cost=Object1.cost.Wholesale_Cost;
}
My question is why can't I perform a deep copy there. I know if I do
this.myRetail=myRetail
in my cash constructor it would work, but then the book says its not a good method;
View Replies
View Related
Mar 10, 2014
class Test3 {
} class MySub extends Test3 {
}
class Test4{
public static void main(String args[]) {
MySub m = new MySub();
}
}
I learned that if a class and its parent class both have no constructors, the compiler is supposed to complain. When I compiled Test4, i got no errors. why did it give no errors?
I read this article : [URL] ....
View Replies
View Related
Jul 14, 2014
In Java code, write class called Student with the following features:
• a private instance variable int studentNumber that is initialized to zero.
• a private instance variable String firstName;
• a private instance variable String lastName;
• a constructor which takes an integer argument and two String arguments to initializes the three respective data items.
• a public method with signature equals(Student s) . . .
So far this is my code :
public class student {
private int studentnumber = 0;
public student () {
firstname= "forename":
lastname="surname":
public student (integer studentnumber, string firstname, string lastname) {
this.firstname= firstname
this.lastname= lastname:
My question is how do i add the integer in the argument do i have to use int =? and how would i go about doing the public signature equals...
View Replies
View Related