Create Only One Instance

Sep 18, 2014

.I was reading head first java book and saw a barbell question on page no. 280,question-"what if you want to write a class in such a way that only one instance of it can be created,and anyone who wants to use an instance of the class will always use that one,single instance?"

View Replies


ADVERTISEMENT

How To Create A Class To Have At Most One Instance

Sep 25, 2013

Can I declare a class as

public static final?

Because I can declare a variable as public static final pi=3.14;

View Replies View Related

Servlets :: How To Create A New Instance For Each New Request

Sep 26, 2014

I want to create a new instance of a Java model class for each new request coming to a servlet.

How to do that without doing that in doGet() or doPost().

View Replies View Related

StringHandler - Create Instance Of Object In A Loop

Oct 26, 2014

I can't figure out where to create the StringHandler object. My code should take a string as input, then create StringHandler object ord with the string input. This should repeat until cancel is pressed, then ord should be sent to the Utskrift-method (a print method).

If I do like this, null is also sent to Utskrift. I dont want that to happen.
If I put StringHandler last in the loop ord can not be resolved.

String text = "";
while (text != null){
text = showInputDialog(null, "Enter text:");
StringHandler ord = new StringHandler(text);
if (text == null){
[Utskrift(ord.getNumber(), ord.getString(), ord.getWords());
break;
}
}

View Replies View Related

Create Instance Of Own Triangle Class And Use One Of Its Methods

Mar 15, 2014

So in the code below I create an instance of my own triangle class and use one of its methods. The thing is I use one of my triangle classes methods in a method other the main method of my main program so I'm thinking it can't access it?

Any way here's the code for my triangle class
 
import java.util.Scanner;
public class QudratullahMommandi_Triangle_06 {
Scanner keyboard = new Scanner(System.in);
private double side1;
private double side2;
private double side3;

[Code] ....

and here's the error message

QudratullahMommandi_S_06.java:46: error: cannot find symbol
{ triangle1.outPut();
^
symbol: variable triangle1
location: class QudratullahMommandi_S_06
1 error

View Replies View Related

How To Pass Object Type To A Method / Then Create Instance

Aug 9, 2014

Essentially, the code I want is:

public void randomCreate(ParentObject obj){
int x = random(0-4); //pseudo
int y = random(0-4); //pseudo
create new ParentObj(x,y);
}

ParentObject is actually abstract, so you would only ever pass one of its children objects to it, and a child object of that type would be created. It seems like there should be a way to pass a type, rather than an object, and then create an instance later down, but I don't know if that is actually possible, or if it is poor programming style.

View Replies View Related

Create A New Instance Carte Of Object Carti Using Constructor

Mar 30, 2014

what have I done wrong n the following code? I'm trying to create a new instance carte of object Carti using the constructor and then to insert a row into a table created with SQL.The error I'm getting is:

Exception in thread "main" java.lang.NullPointerException
at Carti.Carti.InsertCarti(Carti.java:103)
at Main.main(Main.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 28 seconds)

The line Main.main(Main.java:37) is when I try to insert the row.
The line Carti.Carti.InsertCarti(Carti.java:103) is when I do the
PreparedStatement st = conn.prepareStatement("insert into Carti (Id,titlu"
+ ", descriere, autor, editie, anPublicare) values (?,?,?,?,?,?)");

Here is the code (Main and Carti Classes)

import Carti.Carti;
import Imprumut_Carti.Imprumut_Carti;
import Membrii.Membrii;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import java.sql.SQLException;
import java.text.DateFormat;
 
[code]....

View Replies View Related

Create A Class That Includes Three Pieces Of Information As Instance Variables

Oct 9, 2014

Creating a class. Specification are given as:

Create a class called Employee that includes three pieces of information as instance variables:

-Employee ID (string type)
-first name (string type) (default value 'John')
-last name (string type) (default value 'Smith') and
-monthly salary (type double).
-No argument constructor that initializes the three instance variables. The employee id should be generated using the following process:

The employee id should be a combination of first initial, last initial and a number starting from 10001 for the first employee and increasing by one for each employee. e.g. if John Smith is the first employee then its id will be JS10001 and if George Brown is the second employee then its id will be GB10002

-Provide get and set methods for each instance variable. The set method for monthly salary should ensure that its value remains positive - if an attempt is made to assign a negative value, leave the original value.

View Replies View Related

Create Instance Of Class Used To Populate DefaultListModel When JList Item Selected

Jan 28, 2015

New to Java Swing. What I am trying to achieve here is to create an instance of the class used to populate the DefaultListModel when a JList item is selected. All examples I have seen show how to return the text displayed in the JList which really is of no practical use.

I have achieved what I want to achieve in that I am successfuly creating the selected object within my ListCellRenderer class.

For the purpose of testing I am using a call to the JOptionPane.showMessageDialog method to display the id of the selected object.

So, I launch the JFrame, the JList is populated, I select an item from the JList and the id value is displayed in the prompt. All this works fine except for one thing.

When I click OK on the JOptionPane.showMessageDialog prompt, the prompt disappears and reappears. The system seems to be in a loop. It is behaving as if the change or click event handler on the JList keeps firing.

This happens even without the creation of the object:

BookEntry be = (BookEntry)list.getModel().getElementAt(list.getSelectedIndex());

I have scoured the code and object properties to see if I can figure out where this behaviour is coming from without success.

All there is in the JFrame design view is a single JList with a variable name of "list". Everything else is in code as below:

Here is the .java code. Its not that complex

import java.awt.Color;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.swing.DefaultListModel;
 public class NewJFrame3 extends javax.swing.JFrame {
 
[Code] .....

View Replies View Related

Create Instance Of Array Of Several Integers And Prints Data Based On Methods

Apr 15, 2014

I have to make two classes. The first one crates an instance of an array of several integers and prints data (average, greatest, lowest, et cetera) based on the second class, which contains the methods. I'm having a problem with the syntax for the first class required to use the methods.

Here's a shortened version of what I have right now just based on processing the number of integers in the array (because if I can get just one method properly connected, I could figure out everything else).

Driver

import java.util.Arrays;
public class ArrayMethodsDriver
{
//Creates the ArrayMethods object
public static void main(String[] args)
{
int[] a = {7,8,8,3,4,9,8,7};

[Code] ....

When I try to compile this, I currently get the "class expected" error on the count part.

View Replies View Related

Converting Parent Instance To Child Instance?

Mar 7, 2014

I've Parent and child(extends Parent) class To initialize the constructors, I'm injecting from google.juice#injector. Let me show the code,

Parent.class

public class Parent{
private Animal animal;
@inject
Parent(Animal animal){
this.animal = animal;

[code].....

When I do this, ClassCastException is happening. Why is it so? Is there any way to convert instance of parent to child instance.

View Replies View Related

What Does Instance Mean

Jan 16, 2015

in a set of instructions they keep referring to instance versions of things I've heard of before ie "private instance array of String references" (wtf is a string reference?) or "instance string variable" so what does all this mean?

View Replies View Related

How To Get Same Value With BigDecimal For Instance

Apr 7, 2013

In the following example, I compute new_amount_d in 2 different ways and I get 2 different values although it should be the same in theory.

Is there a way to get the same value with BigDecimal for instance?

public class num004
{
public static void main(String[] args) {                    
          double amount_d = 1000;
          double interest_rate_d = 0.03;

[Code] ....

View Replies View Related

Instance Variable For Objects?

Feb 23, 2015

I am working on a project and it asks me to "Provide appropriate names and data types for each of the instance variables. Maintain two GVdie objects" under class fields. I am unsure as to what is being asked when asking for two objects as instance variables and how I would write that...

View Replies View Related

Appropriate Way Of Populating Collection Through Instance

Feb 23, 2015

I have a method that accepts JSONArray as parameter and returns the values of it as ArrayList Object. My question which of these ways is appropriate in populating the ArrayList object this method populates the arraylist upon creation of object (I don't know what the right term to use, but as netbeans IDE suggest, JSONArray object should be final since it was used in inner class.).

private List<String> getStringList(final JSONArray jsonArr) {
return new ArrayList<String>() {
{
try {
for (int i = 0; i < jsonArr.length(); i++) {
add(jsonArr.getString(i));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
};
}

this second method is the usual way of populating collection

private List<String> getStringList(JSONArray jsonArr) {
List<String> strList = new ArrayList<String>();
try {
for (int i = 0; i < jsonArr.length(); i++) {
strList.add(jsonArr.getString(i));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}

What are the advantages and disadvantages between the two? like which is faster? or which consumed larger memory?

View Replies View Related

Changing Value Of Object Instance

Jul 13, 2014

I have been working on a program that is meant to use a class' instructions in a program to add a value to a variable, save it, and present it. This is my class

public class Car
{
//FIELDS
private int yearModel;
private String make;
private int speed;
//METHODS
public Car(int carYearModel, String carMake)

[Code] .....

Whenever I call the accelerate method, a value of 5 is to be added to the speed variable. But whenever I call accelerate, it doesn't increase! I just don't understand why not. I've tried different renditions of adding 5 to speed and it doesn't quite work. I don't get any errors when I compile, just runtime, when it doesn't add 5 to speed.

View Replies View Related

New Object With Instance Variables

Apr 7, 2014

So far in my assignment I have successfully opened a text file. However I am required to do more:

1) As each line of text (containing names and ages) is read a new Runner object is created with its instance variables set thus: ! (Runner class already created )!

- name : set directly set from the value in the file
- agaGroup : can be worked out from the given ages:
< 18 should be 'junior'
> 55 should be 'senior'
the rest should be 'standard'

2) the instance of Runner should be added to the list referenced by the instance variable runners.

I have used if statements to create the junior list, however I do not see the full list of names and ages in the variable runners as I am requested to.

I am sure there is a for loop involved somewhere but I do not know how to:

a) use the for loop in my method
add a new Runner object with the variable mentioned.

I include the code I have done so far as a file - p.s I use Bluej.

public class MarathonAdmin
{
// instance variables
private String runners;
private String age;

[Code] ....

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

One Object / One Instance Variable - Different Values?

Feb 5, 2015

Let's pretend I'm working on an RPG. Like in all RPGs, there are items found all throughout the imaginary world. Each player and NPC can obtain an item. My question will concern those items.

In other words, I'd like to use instances of a class in multiple places of the code. Each instance will have its own, individual values of instance variables, with one obvious exception: itemQuantity should have a different value in playerInventory, npcInventory, etc. Also, I'd like a list of all items that can be found in the game. This list doesn't need itemQuantity at all.

class Items {
String itemName;
float itemWeight;
int itemQuantity;

[Code] ....

The question is: should I really make itemQuantity an instance variable of the Item class? It seems as though for each copy of the Item class I should create a separate copy with different value of itemQuantity, but that's not very efficient. Where is the error in my logic?

What's important is that there may be plenty items in a game and a player may be given power to create new items during the course of the game.

View Replies View Related

Variable In Interface Cannot Be Instance Scope?

May 5, 2014

I'm just wondering why variables in interface can't be instance scope?

interface Test{
int a;
}

And then

Test test = new TestImpl();
test.a=13;

Yes, it violates OO, but I don't see why this is not possible? Since interface is not an implementation, therefore it can;t have any instance scope variable. I can't find the correlation of interface being abstract and being able to hold instance scope variable. There's gotta be another reason. I'm just curious about any programmatic limitation, not deliberate design constraint. the example of programmatic limitation is like when Java forbids multiple inheritance since when different parents have the exact same method, then the child will have trouble determining which method to run at runtime.

View Replies View Related

Accessing Textfield Via JFrame Instance

Jan 25, 2014

I have 1 textfield and 1 button on a JFrame and having 10 such frames stored in ArrayList al and getting the JFrame instance from traversing the ArrayList at execution time ,So is there a way to access textfield using JFrame instance or i have to name the textfield diffrently 10 times for each frame .

View Replies View Related

New Instance Variable Values Not Updating

May 6, 2015

Alright, I have a JavaFX gui that is creating a new instance of data calculation to graph in a chart; however, the data is not updating each time the Platform.runLater() feature executes. Each time an event occurs, a new instance with the same variable name occurs. I use to get methods to retrieve the data I want, so shouldn't the values update each time the new instance is created? This is a very condensed version of what happens with the event, but this is what is not working correctly.

Event:
solarPlot = new SolarTracker();
solarPlot.getElevation();
solarPlot.getAzimuth();
Class constructor :
public SolarTracker() {

[Code] .....

View Replies View Related

Convert Currency Instance To Integer

Jul 26, 2014

I am working with a JFormattedTextField. After adding the text of the FormattedTextField to an LinkedList i want to read it out and sum it up. So I have a problem to convert the String to and integer...

Example:

23.00 - to 23.00
+ 11.00 - to 11.00
--> 34.00

I have tried it with splitting the string but it didn't work. How to do it?

View Replies View Related

Unable To Change Value Of Instance Variable

May 23, 2014

Is there anything wrong on my code?

import java.util.*;
public class Card
{
private String description;
private String suit;
private int value;
private static final String [] cardName {"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Jace","Queen","King","Joker"};

[Code]...

View Replies View Related

Iterate Enum Type Without Instance

Sep 16, 2014

Is there anyway to iterate an enum type without an instance. As some context, consider the following code:

Java Code: public interface GenericChecker
{
public bool isValid(String str);
} mh_sh_highlight_all('java'); Java Code: public class EnumChecker<T extends Enum<T> > extends GenericChecker
{
private Class<T> enumType; //No instance

[code]....

toString method of the enum types has been overridden so that it returns the name assigned to the enum rather than the enum name itself. For example an enum might be SOME_ENUM("Assigned name"), therefore toString returns "Assigned name" rather than "SOME_ENUM". The idea is that a field from a table can be handed to the isValid(String) function on the GenericChecker base, and the derived class will then check to see if the field matches valid data as far as it is concerned.Thus, I can create a whole bunch of checkers easliy:

Java Code: GenericChecker checker1 = EnumChecker<EnumType1>();
GenericChecker checker2 = EnumChecker<EnumType2>();
GenericChecker checker3 = EnumChecker<EnumType3>();
GenericChecker checker4 = SomeOtherChecker(); mh_sh_highlight_all('java');

The problem is, if I use the EnumChecker then the expression "enumType.getEnumConstants()" in the isValid function blows up because enumType is null.

View Replies View Related

Describing The Type Of Instance Variables?

Oct 9, 2014

What is the correct way of describing the type of instance variables?

It is obvious in the case of a primitive type

Example: private int number;

The (data)type of number is integer.

What if the instance variable is an object or a wrapper?

example: private Person person;

the (data?)type of person is an object of the type/class Person?

example: private Integer number;

View Replies View Related







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