Using Setter And Getter Methods Instead Of Altering Variables

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


ADVERTISEMENT

ImageIcon Setter And Getter Methods Not Working

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

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 View Related

Month Class With Constructors And Getter / Setter Methods To Access Attributes

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

Modify And Use A GUI To Set Variables Setter Methods

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

Possible To Set Setter And Getter Various Times

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

Access Getter / Setter Of Bean Class Where It Defined As Member In Another Class?

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

How To Create Public Get And Setter Methods For Private Members Of The Class

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

Accessing Instance Variables And Methods

Oct 24, 2014

I have the following 2 classes:

class Address {
private int a;
public void set_a(int a) {
this.a = a;
}
}
class Person {
private Address address;
}

How do i access the method set_a() (through the "address" in Person) from another class which contains main() ?

View Replies View Related

Variables Over Methods - Unresolved Compilation

Mar 17, 2015

I'm making a java program that can "convert" java to arduino by sending commands over a serial port. I'm using the JSSC library, and using methods to shorten things up a bit.

I've already made the code that starts up the serial port and it does connect. But I've made two different classes for the methods. One for the RXTX and one for the Arduino.

I'm making it so that I can just type:

Java Code:

public static void main(String[] args) {
RXTX.SerialSetup();
Arduino.pinMode(2, 0);
} mh_sh_highlight_all('java');

And it will start the serial port and set pinmode on pin 2 to output.

But when I try it I get this error:

Java Code:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

serialPort cannot be resolved mh_sh_highlight_all('java');

I don't know if its possible to 'send' a variable to a different method.

View Replies View Related

Do Inherited Methods Use Their Instance Variables?

Jan 8, 2014

Do inherited methods use their instance variables or do they use the ones in the method that inherits them?

For example, Class B extends Class A. Class A and B both have the instance variable "potato". A client program tries to use method "cut" using an object of Class B, but class B has no cut method. So, class B uses the "cut" method inherited from class A. What I want to know is will that cut class A's potato or class B's?

View Replies View Related

Object / Methods - Private Instance Variables

Jun 30, 2014

so, i was reading my java book and learning about objects and methods and it starts talking about Encapsulation and mentions that it's good practice to set instance variables as private and instead of accessing the instance variables directly, we should create a set method and get method to get and set the stuff we want to pass to the class containing the object...

for example, in this class, we're passing the integer 70 for object dog one and integer 8 for object dog two for the dog class... and these these 2 integers are sent to the setsize method so we're not accessing instance variable size directly.

i dont quite get it though....if we the programmer are the one deciding what size the integer is for the dog, and the setsize method takes the one.setSize(70) or (8) and puts them in setsize(int s) as s... but only to copy that integer stored in s back to private int size.... why do we even need to bother with making these two extra methods such as setSize, getSize?

in the book it says that... well what if the code gets into the wrong hand and someone writes something like one.setSize(0) then you would get a dog with size 0 which is essentially illogical. but then again, i'm the programmer, and i am the person who writes the code and passing the right integer.The reason for public and private... that part i understand... i can see why if a variable's data can get changed amidst the code during calculations and you dont want it to directly change the original variable and have it mess up the code, but this code from the book just a bad example of demonstrating the reason? since we manually pass the information ourselves and passing it to method setSize... and all setSize does is stores it in another integer, only to copy it right away to size (which is the original private variable we were tryign to protect?

Any simple code to demonstrate how the code might end up changing an instance variable and why we would want to protect it by using private?

class GoodDog {
private int size;
public int getSize() {
return size;
}
public void setSize(int s) {
size = s;

[code]...

View Replies View Related

JSF :: Call Variables Instead Of Methods From A Xhtml Page?

Jun 2, 2014

If I had this code:

<h:dataTable value="#{customer.customerList}" var="c"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
>

And in the server getCustomerList() accessed to database, how many times getCustomerList() would be called from I request the xhtml page?. I have read this would be called several times because of JSF internals and It would be better to store it in a variable and access this variable.

1. Is this true this would be called several times? why?

2. If the previous statement was true, how to avoid it, I mean not call the method from a service?

View Replies View Related

Instance Variables Passed In As Arguments To Static Methods?

Feb 19, 2011

I thought static methods could never use instance variables, because they wouldn't know which instance to look at.

From Head First Java, p. 284: "A static method is not associated with a particular instance - only the class - so it cannot access any instance variable values of its class. It wouldn't know which instance's values to use."

Now I was answering some mock exam questions from Cameron McKenzie's SCJA book, and I don't understand one of the options. On page 205, the last question has an option that says: "Instance variables ... are not visible in static methods, unless passed in as arguments." This option is supposed to be correct. Now... how does that work?

View Replies View Related

Arithmetic Methods Whose Main Method Holds Two Integer Variables

Jan 15, 2015

a. Create an application named ArithmeticMethods whose main() method holds two integer variables. Assign values to the variables. In turn, pass each value to methods named displayNumberPlus10(), displayNumberPlus100(), and displayNumberPlus1000(). Create each method to perform the task its name implies.

b. Modify the ArithmeticMethods class to accept the values of the two integers from a user at the keyboard.

View Replies View Related

Inheritance In Java - Child Class Get Copy Of Methods And Variables Of Parent Class?

Mar 1, 2015

Does child class gets a copy of the methods and variables of parent class?

public class test1 {
public static void main(String a[]) {
Child c = new Child();
c.print();

[Code] ....

why is the output 1?

View Replies View Related

Altering Parent Method Behavior By Overriding Method It Calls

Apr 21, 2014

I have two classes (Daughter and Son) that contain some very similar method definitions:

public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();
d.speak();
s.speak();

[Code] .....

Each of those classes has a "speak" method with two out of three lines being identical. I could move those into a parent class, but I need each of the child classes to continue to exhibit its unique behavior. I'm trying the approach below, which replaces the unique code with a call to a "placeholder" method that must be implemented by each child class:

public class Family {
public static void main(String[] args) {
Daughter d = new Daughter();
Son s = new Son();

[Code] .....

This works and moves the shared code from two places (the Daughter and Son classes) into one place (the new Mother class, which is now a parent class of Daughter and Son). Something about this feels a bit odd to me, though. It's one thing for a child class to override a parent class's methods to extend or alter their behavior. But, here, I've implemented an abstract method in the parent class to alter what happens when the parent class's method (speak(), in this case) is called, without overriding that parent class method itself.

View Replies View Related

Declaring Variable And Using Getter

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

How To Access Getter Method From Different Class

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

Creating A Setter Method?

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

Private Var Won't Save Value Of Public Getter Function From Base C

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

JSF :: PrimeFaces Calendar Not Calling Setter Method

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

NullPointer Exception From Calling A Setter In Array Of Objects

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

Comparing Two Variables

Mar 30, 2014

Let's get it out of the way -- I'm stumped. On something that should be pretty simple to solve. Code follows.

public class Sum {
public static void main(String [] args) {
Double nSum = 0.0;
Double aDouble = 100.0;
for (int i = 0; i < 1000; i++){
nSum += 0.1;

[Code] ....

The output:

100.000000
100.000000
false
false
false
false
false

Process finished with exit code 0

I wrote another simple program and hardcoded the values: aDouble = 100.0; bDouble= 100.0000

Using aDouble.equals(bDouble) returns true, just as one would expect.

So what am I overlooking?

View Replies View Related

JSF :: How To Compare Two Variables

Feb 25, 2014

Having two values

<c:set var="var1" scope="view" value="#{ID1}"/>
<c:set var="var2" scope="view" value="${ID2}" />

I tried in <c:if test=${var1 == var2}>

and eq also

above condition is not working. Both are same object. How to check?

View Replies View Related

Variables In While Construct

Apr 8, 2014

New to java/programming and i cant understand why the pen variable does not display the the correct value ... For example for input 1 ; 2 ; 3 ; 4 both variables will display 10 and i dont understand why pen does not have the value 6 .

import acm.program.*;
public class Chap4_ex12 extends ConsoleProgram {
public void run () {
int pen = 0;
int r = 1;
int sum = 0;
while (r !=SANTINEL) {
r = readInt(" ? ");
pen=sum ;

[code].....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved