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


ADVERTISEMENT

Declaring Object Using Interface Implemented By Its Class Vs Declaring Object Using Class

Apr 8, 2014

Suppose you have a generic Dog class of the pet type that implements a DogInterface of the pet type. What is the difference between;

DogInterface<pet> Rex = new Dog<pet>();

and

Dog<pet> Tye = new Dog<pet>();

In what situations might you want to use Rex instead of Tye?

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

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

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

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

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

Declaring Variables In GUIs

Aug 25, 2014

In most of the GUI examples, it declares the variables right at the start as private.

public class KiloConverterWindow extends JFrame
{
private JPanel panel;
private JLabel messageLabel;
private JTextField kiloTextField;
private JButton calcButton;
private final int WINDOW_WIDTH = 310;
private final int WINDOW_HEIGHT = 100;

In one example though, it declares and creates the different objects in the constructor.

public BorderWindow()
{
setTitle("Border Layout");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

JButton button1 = new JButton("North Button");
JButton button2 = new JButton("South Button");
JButton button3 = new JButton("East Button");
JButton button4 = new JButton("West Button");
JButton button5 = new JButton("Center Button");

Now what I assume, is that for the second example snippet, because it's sole purpose is to show you the Border layout, there are no events tied to any buttons, and there is no data, other than the names of the buttons. With the first snippet, it's purpose was to show the kilometer to miles converter using a GUI. The purpose of making it private is to prevent the data from being altered from outside code. If I have the right idea, I feel like they should have continued to keep their examples consistent.

View Replies View Related

Declaring Parameters - Use Void For

Mar 1, 2015

I want to have parameters that I use the "void" for, in other words it doesn't return anything.

class code
{
void go()
{
int TestStuff t = new TestStuff();
t.takeTwo(12,34)
}
void takeTwo (int x, int y) {
int z = x + y;
System.out.println("Total is:" + z);
}
}

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

What Is The Impact Of Declaring A Method As Final

Nov 14, 2014

1 Can method declared as final be overridden and overloading ?

2 if A is static sub class of B. how to access a method in class A ?

View Replies View Related

Table Booking In Restaurant - Declaring 2D Array

Oct 29, 2014

import java.io.*;
public class Booking {
private Customer[] [] booking = new Customer [7] [tables];
private int count = tables;
private String restaurant;

[Code] ......

View Replies View Related

Declaring Static Int - Illegal Modifier For Parameter

Feb 15, 2014

I accidentally wrote a code differently than what I should've, and I got these errors :

"Illegal modifier for parameter a; only final is permitted"
"Illegal modifier for parameter b; only final is permitted"
"Illegal modifier for parameter c; only final is permitted"

The code that I wrote and gave these errors:

Java Code:

class Math {
public static void main(String[] args) {
static int a = 11;
static int b = 35;
static int c = 29;
//the rest of the code below

[Code] ....

I noticed that I can declare "static int" only under "class Math" and not under "public static void main".(I had to remove "static" if declaring int under "public static void main");

View Replies View Related

Method Implementation Declaring Exception Other Than That Declared In Interface

Aug 31, 2014

The 2 minute drill from page 69 SCJP kathy and bert book, says regarding Interfaces, that - "A legal nonabstract implementing class must not declare any new checked exceptions for an implementation method."

When I try the below given code in eclipse , it does not throw any errors . (Here I have tried to throw NullPointerException from testFunc whereas the interface function throws IllegalStateExc)

package abstracttesting;
public class StaticCheck implements check{
public void testFunc() throws NullPointerException{
// TODO Auto-generated method stub
} public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
interface check{
void testFunc() throws IllegalStateException;
}

View Replies View Related

Declaring Enums - Could Not Find Or Load Main Class

Feb 25, 2014

I've just started, so right now I'm reading about declaring enums, the book lists the following code

enum CoffeeSize {
//8,10 & 16 are passed to the constuctor
BIG(6), HUGE(10), OVERWHELMING(16);
CoffeeSize(int ounces){ //constructor
this.ounces = ounces;

[Code] .....

I'm assuming that code to be in a same file since enums can be declared within and outside a class, so I saved it into a file named "Coffee.java", it compiles just fine from command line but when I try to execute "java Coffee" it throws "Error: Could not find or load main class Coffee"...

View Replies View Related

Declaring Parameters (fields As Protected String) In Java Class

May 19, 2014

I am trying to declare fields as protected String custom.field.1096; in my java class but it does not allow me. Can I not declare the field as above? Is there any workaround to achieve 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

Difference In Variable Assignment Between Constructor And Variable Section

May 21, 2014

Given the case I have an object which is assigned only once. What is the difference in doing:

public class MyClass {
private MyObj obj = new MyObj("Hello world");

private MyClass(){}
//...
}

and

public class MyClass {
private MyObj obj;
private MyClass(){
obj = new MyObj("Hello world");
}
//...
}

Is there a difference in performance or usability? (Given also the case there are no static calls expected) ....

View Replies View Related

Are Terms Local Variable And Member Variable Comparable

Oct 27, 2014

The term "Local variable" is related to scope. That is a local variable is one which is defined in a certain block of code, and its scope is confined inside that block of code.And a "Member variable" is simple an instance variable.

I read in a discussion forum that when local variables are declared (example code below), their name reservation takes place in memory but they are not automatically initialized to anything. On the other hand, when member variables are declared, they are automatically initialized to null by default.

Java Code: public void myFunction () {
int [] myInt; // A local, member variable (because "static" keyword is not there) declared
} mh_sh_highlight_all('java');

So it seems that they are comparing local variables and member variables. While I think a member variable can also be be local in a block of code, isn't it?

View Replies View Related

What Handling Exception And Declaring Same Exception In Throws Clause Achieve

Jan 24, 2014

I was giving a quick skim to some tutorials on the internet where I have found the exception that is handled is also declared in the throws clause of the method wrapping the try-catch block. For a code representation consider the following:

public void methodName() throws IOException {
try {
...
} catch (IOException ex) {
.... TODO handle exception
}

}

View Replies View Related

Declaring Class In Main Class - Constructor Cannot Applied To Given Types

Aug 1, 2014

So i declared a class in main class but it seems there's error when i compile:

constructor xx in class xx cannot applied to given types

This is my java class:

public class trainer extends person{
String classType;
public trainer(String name, String gender, String address, int id, String classType) {
super(name,gender,address,id);
this.classType=classType;

[Code] ....

And this is the way i declared in main class:

trainer tr = new trainer();

And what i want to do is:

tr.toString();

View Replies View Related

Reference Variable - Create Another Variable And Set It Equal To First

Jan 11, 2015

Given a reference variable : Car c1 = new Car();

when we create another variable and set it equal to the first : Car c2 = c1;

we're pointing c2 at the same car object that c1 points to (as opposed to pointing c2 at c1, which in turn points at the car). So if we have code like,

Car c1 = new Car();
Car[] cA = {c1, c1, c1, c1};

are we doing the same? Are we creating four *new* reference variables, each of which points at the same car (again as opposed to pointing them at c1 itself)? I think so, but want to make sure I'm understanding this correctly.

View Replies View Related

How To Use Value Of String Variable Cel1 As Variable Name

May 23, 2014

I have a JFrame jf and JPanel jp on it. jp has five TextFields named cel1, cel2.. cel5. I wish to construct a String Cel + for loop index and run a for loop to reset the values of all the text fields using a single statement such as cel1.SetText("abc"). Similar things can be done in foxfro. How does one do it in java?

View Replies View Related

Declaring Methods For A Class In Its Own Class Whilst Objects Of Class Declared Elsewhere?

Mar 5, 2015

How do you declare methods for a class within the class whilst objects of the class are declared else where?

Say for instance, I have a main class Wall, and another class called Clock, and because they are both GUI based, I want to put a Clock on the Wall, so I have declared an instance object of Clock in the Wall class (Wall extends JFrame, and Clock extends JPanel).

I now want to have methods such as setClock, resetClock in the Clock class, but im having trouble in being able to refer to the Clock object thats been declared in the Wall class.

Is this possible? Or am I trying to do something thats not possible? Or maybe I've missed something really obvious?

View Replies View Related

How To Use Variable In If Statement

Feb 17, 2014

How do I use a variable in an if statement to return a public void method from another class? I've tried:

System.out.print("select 1 - 6: ");
Scanner myScanner = new Scanner(System.in);
myScanner.nextInt();
if (myScanner.nextInt()==1) {
carSelection colour = new carSelection();
colour.carSelection();

The method colour in class car selection is just 4 print line statements? I've // out the if statement to see if it is correctly calling the method and displaying the data and it is?

View Replies View Related







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