How to create an array of objects - java

I thought this was pretty simple, because I am pretty sure I have done it before, but I cant seem to get this to work.
My class is:
public class City
{
String start = null;
String end = null;
int weight = 0;
}
and I am doing:
City cityGraph[] = new City[l];
When I try to access cityGraph[x].start for example, I get a null pointer exception, so I figured I need to initialize every element in the array as well, so I do:
for(int j = 0; j < l; j++)
{
cityGraph[j] = new City();
}
but it is giving me this error:
No enclosing instance of type Graphs is accessible.
Must qualify the allocation with an enclosing instance
of type Graphs (e.g. x.new A() where x is an instance of Graphs).
I have no idea what this means, or how to fix it. Any help would be appreciated!

That can happen when you have declared public class City as an inner class of public class Graphs like so
public class Graphs {
public class City {
}
}
This way the City cannot be constructed without constructing a Graphs instance first.
You'd need to construct the City as follows:
cityGraph[j] = new Graphs().new City();
// or
cityGraph[j] = existingGraphsInstance.new City();
This makes honestly no sense. Rather either extract the City into a standalone class,
public class Graphs {
}
public class City {
}
or make it a static nested class by declaring it static.
public class Graphs {
public static class City {
}
}
Either way, you'll be able to construct a new City by just new City().
See also:
Java Tutorials - Learning the Language - Classes and Objects - Nested Classes

It seems that your class is not a static inner class, which means that it requires an instance of the outer class in order to be instantiated.
More on Static vs Inner classes
http://mindprod.com/jgloss/innerclasses.html

I actually have the answer to my own question. Making the class static fixed it. I don't know why I didn't think of this until after I posted... Hopefully this will help someone in the future.

Related

How to get information back and forth between classes?

Hello im learning how to handle multiple classes in one code but here is a problem i couldnt figure out how it is called nor an answer to it. So i have one variable x in Back class, i get it to the main then i want to push it back to the back class and then again pull it to the main. Its a simplified code so i can use it as an example to change variables in other classes depending on certain condintions. Currently its not working.
package Classes;
public class Main {
public static void main(String[] args) {
Back Q = new Back();
double f = Q.x;
System.out.println(Q.g);
}
}
//-------------------
package Classes;
public class Back {
Main K = new Main();
double x = 10;
double g= K.f; //f cannot be resolved or is not a field
}
First of all you need to read more about access modifiers in java. There are few main things that you must understand:
Difference between static and non-static members;
Difference between different access levels (public, protected, package-private/default and private);
Local variables.
These things can help you to decide what type of variables you need.
Right now you're trying to get an access from a static main method to a non-static package-private variable in a neighbor class via newly created object, and is ok.
But you also try to get an access from the inside of a non-static object to a local variable that is defined in a static method - this is impossible. Instead, it is probably better to introduce setter methods or introduce other methods that accept external parameters.
The attribute x in class Back is package-private, so it can be accessed directly via the Back object called Q you create in main().
In the class Back you try to access the attribute f of the class Main which is references by the object called K. But the class Main does not define any attributes.
You only have a local variable called f in the scope of the main() method that has been definied in class Main.
A possible solution could be something like this. But I don't know what problem you want to solve with your code. So here is just an idea that should compile...
package Classes;
public class Main {
double d = 5.0;
public static void main(String[] args) {
Back Q = new Back();
double f = Q.x;
System.out.println(Q.g);
}
}
//-------------------
package Classes;
public class Back {
Main K = new Main();
double x = 10;
double g = K.d;
}

Grab public member of abstract class in Java

I know that when I generate an abstract class and give it public members I can grab them from the child class. But I want to do exactly that, but on a general basis. For example:
public abstract class Tile {
public int member = 0;
}
Now I create a lot of subclasses (at least 20). I have a list of mixed subclasses and I want to grab that public member.
ArrayList<Tile> tiles = new ArrayList<>();
...
for (int i = 0; i < tiles.size(); i++) {
tiles.get(i).member++; // get and do something useful with member
}
Of course the list does (as far as I know) hold subclasses of Tile. I want to be able to grab the public member from the list of subclasses without having to know which subclass it is. Is there a way to accomplish this?
For clarity, this will not compile and the editor doesn't recognize the global member on the line tiles.get(i).member.

Is overriding static field with static block bad practice?

I want to create data structures to capture the following ideas:
In a game, I want to have a generic Skill class that captures general information like skill id, cool down time, mana cost, etc.
Then I want to have specific skills that define actual interaction and behaviours. So these would all extend from base class Skill.
Finally, each player will have instances of these specific skills, so I can check each player's skill status, whether a player used it recently, etc.
So I have an abstract superclass Skill that defines some static variables, which all skills have in common, and then for each individual skill that extends Skill, I use a static block to reassign the static variables. So I have the following pattern:
class A {
static int x = 0;
}
class B extends A {
static {
x = 1;
}
}
...
// in a method
A b = new B();
System.out.println(b.x);
The above prints 1, which is exactly the behaviour I want. My only problem is that the system complains about I'm accessing static variable in a non-static way. But of course I can't access it in that way, because I only want to treat the skill as Skill without knowing exactly which subclass it is. So I have to suppress the warning every time I do this, which leads me to think whether there is a better/neater design pattern here.
I have thought about making the variables in question non-static, but because they should be static across all instances of the specific skill, I feel like it should be a static variable...
You should generally avoid such use of global state. If you know for sure that the field x will be shared across all instances of all subtypes of the base class, then the correct place to put such a field is probably somewhere other than the base class. It may be in some other configuration object.
But even with your current configuration, it just does't make sense since any subclass that modifies the static variable will make the variable visible to all classes. If subclass B changes x to 1, then subclass C changes it to 2, the new value would be visible to B as well.
I think that the way you described in the question, every subclass should have its own separate static field. And in the abstract base class, you can define a method to be implemented by each subclass in order to access each field:
abstract class A {
public abstract int getX();
}
class B extends A {
public static int x = 1;
public int getX() {
return x;
}
}
class C extends A {
public static int x = 2;
public int getX() {
return x;
}
}
As already pointed out by some answers and comments, your approach won't work the way you want because every static block changes the static variable for all classes extending A.
Use an interface and instance methods instead:
public interface A {
int getX();
}
-
public class B implements A {
private static final int X = 1;
#Override
public int getX() {
return X;
}
}
-
A myInstance = new B();
System.out.println(myInstance.getX()); // prints "1"

How do I access an array from a parent class in a child class?

I have a class where arrays are globally declared and public these arrays are initialized though methods in this class. They are not inside of a constructor. I have another class where I have used extends to allow me access to these values. Of course, I am recieving a null pointer exception. How would I go about fixing this? I do not need to override these arrays. JUst need to use them inside of methods to fill other arrays.
I have been at this for awhile now. My experience with java is still pretty minimal.
Any suggestions would be appreciated. Thank you everyone
An example of what I am talking about:
public class Parent{
public double hey[ ];
public double [] fillHey(){
hey = new double[57]
for(int k = 0; k<57; k++)
{
hey[k] = k+2;
}
}
}
The child class:
public class Child extends Parent{
public double you[ ];
public double[ ] fillYou(){
you = new double[57];
for(int k = 0; k<57; k++)
{
you[k] = (k+2) * hey[k];
}
}
}
You did not instantiate hey array in the constructor of either class so it is still null when you use it in the child class.
You can either
instantiate it in a constructor
or instantiate it inside fillYou() method in the child class (before it's used).
If you want to access to the hey[] from the child class, you must call it like this:
double a[] = super.hey;
Hope it works for you!

What is the purpose of nested classes in Java?

I've seen this sample code from Oracle Website about Java ?
public class Parent {
class InnerClass {
void methodInFirstLevel(int x) {
// some code
}
}
public static void main(String... args) {
Parent parent = new Parent();
Parent.InnerClass inner = parent.new InnerClass();
}
}
What is the purpose of the construct parent.new InnerClass()?
What kind of classes would be suited to such construction?
The title may be misleading: I understand everything about this construct.
I just don't understand where and when to use this Java feature.
I found another syntax to do the same: Java: Non-static nested classes and instance.super()
There are lot's of references about this structure, but nothing about the application.
[References]
Java inner class and static nested class
Java: Static vs non static inner class [duplicate]
what is the use of inner classes in java ? is nested classes and inner classes are same? [duplicate]
Java: Static vs non static inner class [duplicate]
What is the purpose of parent.new InnerClass()?
This is for demonstration - using this mechanism to construct an inner class is rare. Normally inner classes are created only by the outer class when it is just created with new InnerClass() as usual.
What kind of classes would be suited to such construction?
Look at Map.Entry<K,V> for a classic example. Here you can see an inner class called Entry that should be created by all classes that implement Map.
I see many answers here explaining the use of inner classes, but as far as I can see, the question is about the specific construct parent.new InnerClass().
The reason for that syntax is very simple: an instance of an inner class must belong to an instance of the surrounding class. But since main is a static method, there is no surrounding Parent object. Therefore, you must explicitly specify that object.
public static void main(String[] args) {
// this results in an error:
// no enclosing instance of type Parent is available
InnterClass inner = new InnerClass();
// this works because you specify the surrounding object
Parent parent = new Parent();
InnerClass inner = parent.new InnerClass();
}
I'm searching for a use of this construct in the standard packages, but so far I haven't found an example.
Inner classes nest within other classes. A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:
Static member classes
Member classes
Local classes
Anonymous classes
the most important feature of the inner class is that it allows you to turn things into objects that you normally wouldn't turn into objects. That allows your code to be even more object-oriented than it would be without inner classes.
public class DataStructure {
// create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
// inner class implements the Iterator pattern
private class InnerEvenIterator {
// start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
// check if a current element is the last in the array
return (next <= SIZE - 1);
}
public int getNext() {
// record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
public static void main(String s[]) {
// fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
}
}

Categories