I have a basic question in Java:
Consider I have
public void initialize(My_Class my_context) {
super.initialize(my_Context);
}
public void work(My_Class2 elt) {
String text = elt.getText();
My_Class3 var1 = new My_Class3();
String new_text = var1.my_method(text);
I am having a problem because I am calling the work method many times, and each time it instantiates a My_Class3 object, which takes a lot of time. I would like to move the instantiation in the initialize method so that it is performed once.
In order to do that, I tried to move
My_Class3 var1 = new My_Class3();
into initialize and set it as a global variable so that var1 is found in the different calls of work. However, I cannot set it into a static variable. I am guessing this has something to do with the visibility of the initialize method, but I cannot change it.
How can I instantiate a var1 variable of type My_Class3 in initialize and call it in work?
My_Class3 var1;
public void initialize(My_Class my_context) {
super.initialize(my_Context);
var1 = My_Class3();
}
public void work(My_Class2 elt) {
String text = elt.getText();
String new_text = var1.my_method(text);
}
Related
I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList;
public class Ballot {
private ArrayList<Candidate> ballot;
private String officeName;
public Ballot(String officeName) {
this.officeName = officeName;
ArrayList<Candidate> ballot = new ArrayList<Candidate>();
}
public String getOfficeName() {
return officeName;
}
public void addCandidate(Candidate c) {
ballot.add(c);
}
public ArrayList<Candidate> getCandidates() {
return ballot;
}
public static void main(String[] args) {
Ballot b = new Ballot("Election");
b.addCandidate(new Candidate("Sarah", "President"));
System.out.println(b);
}
}
When I try to run the document, it throws a NullPointerException. What am I doing wrong?
The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:
public Ballot(String officeName) {
this.officeName = officeName;
ballot = new ArrayList<Candidate>(); // Here!
}
You're not initializing your list of candidates properly in the Ballot constructor. You need to do:
this.ballot = new ArrayList<Candidate>();
Right now you're just creating a local variable named ballot in the constructor which shadows the actual class field. Since it has never been initialized, you end up getting a NullPointerException when you eventually try to add an element to it.
Also, as a best practice, use interfaces instead of the concrete type. This makes it easy to change implementations later. So instead of defining the field as private ArrayList<Candidate> ballot;, define it as private List<Candidate> ballot;.
As simple that you are not using this object. You are never initiliazing your object
Correct way
public Ballot(String officeName) {
this.officeName = officeName;
this.ballot = new ArrayList<Candidate>();
}
You're overriding your class variable with a local variable of the same name. Either initialize the list directly
private List<Candidate> ballot = new Arraylist<>();
or initialize it in the constructor with
ballot = new ArrayList<>();
FYI: You shouldn't assign implementation classes for your local variables and return values if you can help it. "ballot" should just be the List interface as should the getter. That way if you ever want to change the implementation, you don't have to change everything. It could be an ArrayList, LinkedList, Stack, Vector, etc and it won't matter because they're all using the List interface.
I have an abstract class which is supposed to have an (int) attribute that can't be modified after initialization and is pre-set to 1; what is the best way to do it?
Should I make it final?
The requirement is that inside the class I will have one and only one constructor(with parameters), and no setters.
If so, how do I make it 1 by default if it's final and (I suppose) I'm going to initialize it in the constructor?
Thanks!
As a matter of fact your can even hard code it, if it will always be a constant value.
For example if your variable should always be 25 you can do something like this:
public abstract class Test
{
protected final int pressure = 25;
//Constructor
public Test()
{
// TODO Auto-generated constructor stub
}
}
But if you evaluate the value on runtime you need to set it with in the constructor of the Object:
public abstract class Test
{
protected final int pressure;
//Constructor
public Test(int pressure)
{
this.pressure = pressure;
}
}
Note that in this case the variable must not be assigned earlier!
The question, if a final variable should be used depends on it's purpose. A final variable can only be assigned once over it's entire lifetime. If you have to modify it in any kind you should not use it.
You could use constructor overloading to achive this. See the example:
public abstract class TestClass{
private final int otherParam;
private final int fixedParam;
public TestClass(final int otherParam){
this.otherParam = otherParam;
this.fixedParam = 1;
}
public TestClass(final int otherParam, final int fixedParam){
this.otherParam = otherParam;
this.fixedParam = fixedParam;
}
}
You should use a constructor with parameters to set your initial values. Then, as you say, don't create any setter, and be sure your fields are private, so that no one can access it.
This way, you will do what you want, having fields initialized but never change after that.
first post and first question.
I am a java beginner so I apologise in advance if my question is very basic, but I have tried for 2 days to find the answer on Internet and on StackOverFlow without success
What I am trying to do: I want to "set" the value of a variable, and then "get" it back multiple other times.
What is happening: the first time that I "get" it, it (correctly) returns the value that I initialized. the following times it returns "null"
Here the code
1) Main class
public class Provasetgetaltraclass {
public static void main(String[] args) {
set_e_get_1 set_e_get_1Obj = new set_e_get_1();
set_e_get_1Obj.execute_var_to_set_e_get1();
set_e_get_1Obj.execute_var_to_set_e_get2();
}
}
2) class with the actions
public class set_e_get_1 {
public void execute_var_to_set_e_get1(){
var_to_set_e_get var_to_set_e_getObj = new var_to_set_e_get();
var_to_set_e_getObj.setname("test");
System.out.println(var_to_set_e_getObj.getname());
}
public void execute_var_to_set_e_get2(){
var_to_set_e_get var_to_set_e_getObj = new var_to_set_e_get();
System.out.println(var_to_set_e_getObj.getname());
}
}
3) class with the variable and the set and get methods
public class var_to_set_e_get {
private String name;
public void setname (String new_name){
name = new_name;
}
public String getname (){
return name;
}
}
4) the result, when I run the main, is
test
null
(what I would like is test and test)
I don't want to store the variable in a database or a file unless necessary, as I'd like to have this working on the fly
If you can help me I'd really appreciate it
Many thanks
What happens is that in each call of the methods execute_var_to_set_e_get1 and execute_var_to_set_e_get2 you are creating different objects.
In the first one you are setting name to a String, but in the last, you are not doing that.
So, it will be null (by default).
Note: The behavior that you have described is of a static attribute. If you declase name as static, it will be shared between all the instances.
Your two methods execute_var_to_set_e_get1 and execute_var_to_set_e_get2 each create a different object of var_to_set_e_get class. You set the value of the property only in one of them, so of course it will be null in the other.
If you want the value you stored in the first object to be available in the second method, your first method has to return the object it creates, and the second method should accept that object :
public var_to_set_e_get execute_var_to_set_e_get1(){
var_to_set_e_get var_to_set_e_getObj = new var_to_set_e_get();
var_to_set_e_getObj.setname("test");
System.out.println(var_to_set_e_getObj.getname());
return var_to_set_e_getObj;
}
public void execute_var_to_set_e_get2(var_to_set_e_get var_to_set_e_getObj){
System.out.println(var_to_set_e_getObj.getname());
}
public static void main(String[] args) {
set_e_get_1 obj = new set_e_get_1();
var_to_set_e_get v = obj.execute_var_to_set_e_get1();
obj.execute_var_to_set_e_get2(v);
}
I am new to java.
I want to know how I can use the variable in the whole java class and keeping the value of it. Suppose in a method I fill the variable with a value and I want to use the value of it in another method.
public class Test {
public String id;
public void includeClient() {
String id = baseClass.createCleint();
}
public void removeClient() {
System.out.println(id);
}
}
in second function it returns null. Any idea?
In the method includeClient() you assigned the value to a local variable having the same name as the instance variable. The other method (which, BTW, can't have the same signature as the first method) sees the instance variable, which is still null.
Change it to :
public void includeClient() {
id = baseClass.createCleint();
}
Remove String from String id = baseClass.createCleint(); as it is local variable for the method and will be assiged the value when you call method and garbage collected after the execution of method and not accessible outside the method.
In short you are not assigning value to the variable declared at class level but you are creating another one.You better use Constructor to perform initialization.
Secondly you have declare public void includeClient() { twice I bet it's typo.
public class Test {
public String id;
public void includeClient() {
id = baseClass.createCleint();
}
}
public class Test {
public String id;
public void includeClient() {
String id2 = baseClass.createCleint();
System.out.println(id2);
id = id2;
}
public void includeClient2() {
System.out.println(id);
}
}
Use this to understand and test.
List of changes made -
Changed second method name to make it unique
Assigned return value to local variable named different than class member variable.
First print return value to check what it is returning
Assign local value to member variable.
Note: You still need to read a lot about java. Just keep practicing.
Replace:
String id = baseClass.createCleint();
by
this.id = baseClass.createCleint();
or
id = baseClass.createCleint();
An important thing to note about this is that there's two ways to share a variable like this - you can have each object of the class have its own copy of the variable, or you can have every object of the class share the same one variable. The keyword static lets you do the latter:
class Test {
public String message;
}
class TestStatic {
public static String message;
}
If you have instances of the first class, they behave like each instance has its own message:
Test testA = new Test();
Test testB = new Test();
testA.message = "Hello!";
testB.message = "Greetings!";
System.out.println(testA.message);
System.out.println(testB.message);
But with the second class, what happens is that the class itself has a message and all instances of the class refer to it, so there's only one message that's shared between all of them:
TestStatic testA = new TestStatic();
TestStatic testB = new TestStatic();
TestStatic.message = "Hello!";
System.out.println(testA.message);
System.out.println(testB.message);
Note that we didn't set message using either testA.message or testB.message as above - we set it using the class with TestStatic.message. This is because message doesn't really belong to either testA or testB, it belongs to the class and testA and testB simple have access to their class's members.
I'm trying to create an object and add it to an array I created as a parameter GUI object I constructed. For some reason I keep getting TheDates cannot be resolved to a Variable.
Object being constructed:
public static void main(String[] args)
{
DateDriver myDateFrame = new DateDriver();
}
//Constructor
public DateDriver()
{
outputFrame = new JFrame();
outputFrame.setSize(600, 500);
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String command;
Date [] theDates = new Date[100]; //this is the array I am having issues with
int month, day, year;
...
}
This is where my problem with theDates is:
public void actionPerformed(ActionEvent e)
{ //The meat and Potatoes
if ( e.getSource() == arg3Ctor)
{
JOptionPane.showMessageDialog(null, "3 arg Constructor got it");
int month = Integer.parseInt(monthField.getText());
int day = Integer.parseInt(dayField.getText());
int year = Integer.parseInt(yearField.getText());
theDates[getIndex()] = new Date(month, day, year);//here is the actual issue
}
}
I don't know if I'm over thinking it or what, I've tried making the array static, public, etc. I've also tried implementing it as myDayeFrame.theDates.
Any guidance is greatly appreciated
You likely have a scope issue. theDates was declared in the constructor and is visible only in the constructor. A possible solution: declare it as a class field. Sure initialize it in the constructor, but if it is declared in the class, it is visible in the class.
You are defining theDates as local variable in the constructor, thus its scope is limited within the constructor. Instead, declare it as a field of the class:
private Data[] theDates;
// ...
public DateDriver()
{
theDates = new Date[100];
// ...
}
1. You have defined theDates, which is an Array Object Reference Variable inside the Constructor, so its having its scope inside the Constructor itself.
2. You should declare the theDates at the class scope, so it will be visible throughout inside that class.
3. And it will be better if you use Collection instead of Array, go for ArrayList
Eg:
public class DateDriver {
private ArrayList<Date> theDates;
public DateDriver() {
theDates = new ArrayList<Date>();
}
}