so I've been wracking my brains over why this isn't working for an hour now. I have two classes, class One containing an ArrayList of ArrayLists and a method to add another element to that list, and class Two, from which I'm trying to access that method.
public class One
{
private ArrayList<Element> myarraylist;
public One()
{
myarraylist = new ArrayList<Element>();
}
public void addElement(String name)
{
myarraylist.add(new Element(name));
}
}
//Element being another class
public class Two
{
One database;
public static void main(String[] args)
{
Two two = new Two();
two.startMenu();
}
public Two()
{
One database = new One();
}
public void addElem()
{
Scanner keyboard = new Scanner(System.in);
String name = keyboard.next();
database.addElement(name);
}
}
//where startMenu is just a small multiple choice menu thingy
Problem is, when I try to run through it and I get to the last line, I get the message: java.lang.NullPointerException
I tried inspecting the objects (I use BlueJ), and the ArrayList is initialized when I just make an instance of class One, but when I make an instance of class Two, the database instance is null.
Thanks in advance for your answers :D
The problem is at the following lines
public class Two
{
One database;
public Two()
{
One database = new One();
//this variable is not the same as the one declared outside the constructor
}
When declaring a variable in a method which has the same name as the variable declared in the class, the modifications which happen on the variable declared inside the method will not be seen in the variable outside the method(because the 2 variables are different). The variable in the method is shadowing the variable from the class.
To differentiate between the two variables you must use the this keyword
this.database = new One();
The final solution should be
public class Two
{
One database;
public Two()
{
this.database = new One();
}
The reason you get the NullPointerException when doing database.addElement(name); is because in your example the database is not instatiated beacause the object created is stored in a different variable named database and not the one declared as a class attribute.
Related
I am making a simulator for solving problems in Java. I want to create a task where a person needs to create class A and then in class B, in the main method, create objects of class A. The problem is that I don't know how to check the number of created objects, or at least the fact that objects were created. Can I check the creation of objects? Without making changes to classes A and B ?
public class A {
//some code
}
class B {
public static void main(String[] args) {
//User will have to create an object of class A here
}
}
You can check the number of objects created in a class by keeping a static variable and increment it upon creation automatically. For example, for class A:
class A {
private static int noOfObjects = 0;
{
numOfInstances += 1;
}
//constructors and other methods
public static int getNumOfInstances() {
return numOfInstances;
}
}
Remember, static variables initialized only once, and they're shared between all instances.
I'm trying to view the elements of an ArrayList in a different class but it shows that there is nothing. In the other class, you can see the element in the ArrayList though.
Here are the codes.
First class
import java.util.ArrayList;
public class Test {
ArrayList<String> inventory = new ArrayList<String>();
public void test() {
inventory.add("item");
}
public void check() {
System.out.println(inventory);
}
}
Second class
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
System.out.println(testObj.inventory);
}
}
Main class
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
Test2 test2Obj = new Test2();
testObj.test();
testObj.check();
test2Obj.test2();
}
}
Output
[item]
[]
In java Class level variables are Object associated until unless they are not declared static.
By means of Object associated is that when a object is initialized with new keyword in Java all Object will be having it's own memory and own class variables.
In your case inside main method when you create a Object of Test class and when you create a another test class object inside Test2 class, both will be totally independent of each other. And both will be having their own memory and own variables.
If you want that to get the updates of inventory variables from first object to be available in another object you need to declare it as static and should be initialized inside static block. Static variables are shared across all objects of class. As below:
static ArrayList<String> inventory;
static {
inventory = new ArrayList<String>();
}
In your main method, you call the method that handles adding operation yet you do not call any add methods in the second class and in your main method.
testObj.test();
testObj.check();
This one shows that you add an item into the arraylist and show it. But in the second class you do not add anything but calling it. Therefore there is no way to show any element from that method. What has should be done is that you just need to call the adding method inside of the second class and then try to use the display method.
You didn't call test() method in Test2 class.
To make it work change the Test2 class as follows.
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
testObj.test();
System.out.println(testObj.inventory);
}
}
I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:
public class Game{
private int randomIndexX;
protected String spawn(){
randomIndexX = randomGenerator.nextInt(10);
return null;
}
protected String test(){
System.out.println(this.randomIndexX);
return null;
}
}
public class Player extends Game{
protected String getNextAction(String command) {
switch(command){
case "test":
test();
break;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Player player = new Player();
game.spawn();
player.getInputFromConsole();
}
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().
So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:
private static in randomIndexX;
As it's value won't change depending on an object instance.
So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):
public static int getRandomIndex(){
return randomIndexX;
}
So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:
System.out.println(Game.getRandomIndex());
The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:
public static void setRandomIndex(int n){
randomIndexX = n;
}
And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.
For example, the code below will set value of randomIndexX to 5 and then print it in the console:
Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
The first problem I can see is that you don't have a constructor.(Optional)
(If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.
The second problem I can see is that you missing the end bracket.
Fix shown below.
public class Game
{
private int randomIndexX;
protected String spawn()
{
randomIndexX = 0;
return null;
}
protected String test()
{
System.out.println(randomIndexX);
return null;
}
}
You can construct it and trigger any methods you wish:
Game game = new Game();
game.spawn();
game.test()
I have a question concerning the use of objects...
I have a class called Area which contains a few methods. I want to access these methods in another class in which an Area object is created.
public class calcAreaObj {
Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Why is it when the class is created as above I get an error("Cannot make a static reference to non-static field areaObj. But when the source code is written such that the Area object is initiaized inside the main statement as below there are no errors...
public class calcAreaObj {
public static void main(String[] args){
Area areaObj = new Area();
areaObj.area(2,3,4);
}
}
Is this because in the first case the Area object is initialized outside of a static statement? If so, why does this matter?
This is because when defined at class scope, areaObj is specific to each instance of calcAreaObj. That's not really what you want, since main is a static method (and so doesn't have an instance of calcAreaObj associated with it). You can either use the second code sample you posted, or you can modify the first one as follows:
public class calcAreaObj {
static Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Additionally, if areaObj doesn't have any state, in this case, you could always declare Area.area as static.
In the first example areaObj is a non-static member of calcAreaObj. This means it can only be accessed using an instance of calcAreaObj.
new calcAreaObj().areaObj.whatever(); //this will work
calcAreaObj.areaObj; //areaObj isn't a static member, won't work
In short: the non-static member doesn't even exist as long as you haven't created an instance of calcAreaObj. In the second example, it's in scope of the method and thus accessible.
For the first situation your creating a local variable for the class which has no relation with the object used in the main. Therefore you have to initialize the object again in the main.
There is a rule: that any block has it's own variables. So if you initialize a variable in block and try to use it outside the block that will give you an error.
For example:
public static void main(String [] arg){
{ Area a = new Area(); }
double number = a.area
}
this doesn't work ...
I wish it is clear
I know that this(...) is used to call one constructor of a class from another constructor. But can we use new for the same?
To be more clear on the question, is Line-2 is valid? If it is (as the compiler did not complaint), why the output is null not Hello?
class Test0 {
String name;
public Test0(String str) {
this.name= str;
}
public Test0() {
//this("Hello"); // Line-1
new Test0("Hello"){}; // Line-2
}
String getName(){
return name;
}
}
public class Test{
public static void main(String ags[]){
Test0 t = new Test0();
System.out.println(t.getName());
}
}
It is valid but it's creating a completely separate instance of Test0 (more specifically an instance of an anonymous subclass of Test0) inside that constructor, and it's not being used anywhere. The current instance still has the field name set to null.
public Test0() {
// this creates a different instance in addition to the current instance
new Test0("Hello"){};
}
Note that if you call the new operator with the no-argument constructor, you would get a StackOverflowError.
What you're trying to do is accomplished by the code you commented out:
public Test0()
{
this("Hello");
}
Line 2 is valid statement. That is why compiler didn't show up any errors. But there you are creating an anonymous object. It will vanish soon after you exit from the constructor. Therefore the value is still null becuase nothing was assigned to that.
new Test0("Hello"){};
Above line will create an anonymous instance of Test0 class and assigned the value of Hello to the name variable. But since you are not referring the created anonymous instance, it will get disappear from the immediate after line. So still you haven't assigned a value to the name variable of the instance that calls the particular code segment. Therefore name is null
In the memory it is like
Because you create a new instance of Test0 with name "hello" but never use it.
public Test() {
new Test0("hello") // nothing is referencing this new object
}
You simply creating an object inside another constructor but it will have no effect on the instance being created by the first constructor call.
You can do this but the result of this new usage will be gone at the end of the constructor. Especially, t.name will be null.
Use this("Hello").
Name is the instance variable. Instance variables are object-specific.
With new Test0("Hello"); you are creating a new instance of Test0.
If you would like to have t.getName() return "Hello" [I mean field value independent of object], change the name field to static:
static String name;
You can display output by using new keyword through below code..Since u have used public Test0(){new Test("Hello){};" here {} braces are not important..so when test0() constructor is called...Inside this constructor test0(args); is being called bt in first constructor u didnot displayed output..where will be your "Hello" will get displayed..so just edit
`
public test0(String str)
{
this.name=str;
System.out.println(str);
}`
And you will have ur desired output..See my below code..
class test01{
public test01(String str)
{System.out.println(str);
}
public test01(){
new test01("Print");
}
}public class Const {
public static void main(String args[])
{test01 t = new test01();
//System.out.println(t.getName());
}}
The output of this code will give u required String