I would like to ask if there is a more elegant way to write the following code:
public class MTree {
class MTreeObject {
double[] vector;
}
class RoutingObject extends MTreeObject {
double radius;
}
class LeafObject extends MTreeObject {
int id;
}
class Node {
LinkedList<MTreeObject> list;
}
class InnerNode extends Node {
LinkedList<RoutingObject> list;
}
class LeafNode extends Node {
LinkedList<LeafObject> list;
}
public static void main(String[] argv) {
MTreeObject object = new RoutingObject();
Node node = new InnerNode();
((InnerNode)node).list.add((RoutingObject)object);
}
}
the problem is that if I have for example:
class Result {
Node node;
}
and then call in main
public static void main(String[] argv) {
Result result = new Result();
MTreeObject object = new RoutingObject();
result.node = new InnerNode();
result.((InnerNode)node).list.add((RoutingObject)object);
}
it doesn't work the way I want. Well I could also do:
newnode = result.node
((InnerNode)newnode).list.add((RoutingObject)object);
but then I would have too much variables in my more complex code...
The problem is you have declared all your classes as inner classes of MTree. An instance of your inner classes can exist only within an instance of the outer class (MTree).
Try making your classes (RoutingObject, LeafObject, etc.) stand alone classes rather than nested or
to instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
MTree mtree = new MTree();
MTree.Node node = mtree.new Node();
See: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Not quite sure from your example what you are trying to accomplish, my guess best guess is you should just not use nested classes. Hope this helps.
Related
I'm trying to store all subclasses of A which are constructed by super() in the array child (in this case B). All the children are in the same package. This is my approach but I don't know how the class could store itself inside an array or pass itself as argument to super().
class A {
static int i = 0;
A[] child = new A[10]
int someval;
A(int val){
someval = val;
child[i] = ???;
i++;
}
}
class B extends A{
B(){
super(val);
}
}
Is this even Possible? With my approach B will only be added when a new B() is created? Is it possible to get a complete array without creating a new object?
public class A {
private static final List<A> instances = new ArrayList<>();
public A() {
instances.add(this);
}
public static List<A> getInstances() {
return instances;
}
}
Now A.getInstances() can be called whenever you like, and will contain instances of anything that extends A.
I am working on a problem where I implement different Linked lists. All the list classes include two inner classes; a Node-class and an Iterator-class.
These inner classes are entirely identical to each other. In the Iterator-class, some of the methods rely on accessing information from the outer class, which works fine. Is there a way to do this in java, so that I would not need to include the very same code in all my different list-classes? I feel clueless - I just don't know where to look.
This is what my Node-class looks like:
class Node{
Node next;
Node previous;
private T data;
Node(T inn){
data = inn;
}
public Node getNesteNode(){
return next;
}
public T getData(){
return data;
}
}
Edit: I realize the Node class is relying entirely on itself.
Here is my simple Iterator:
class LenkeListeIterator implements Iterator<T>{
private int field = 0;
Node denne = forste;
#Override
public boolean hasNext() {
return field!= storrelse();
}
#Override
public T next() {
T data = denne.getData();
denne = denne.getNesteNode();
field++;
return data;
}
}
By definition, an inner class is an intrinsic part of the class containing it. It can only be shared with subclasses, not peers or classes outside the hierarchy of the parent class entirely.
There's nothing in your Node class that requires it to be an inner class, so you could just make it standalone. But if there were something that made it need to be an inner class, you could put all the parts that don't into a standalone class that is then subclassed in each of the parent classes to provide it with access to the parent's inner data.
E.g. (roughly):
abstract class Example {
protected int something;
public void logic() {
SomeType data = this.getParentData();
/* ...do something with `data`... */
}
abstract protected SomeType getParentData();
}
Then an inner class in, say, Container would subclass it and provide getParentData.
class Container {
private SomeType data;
class ContainerExample extends Example {
protected SomeType getParentData() {
return data;
}
}
}
Is it possible for the nested inner classes ABar and BBar to access main class's variables? For example:
public class Foo {
public ABar abar = new ABar();
public BBar bbar = new BBar();
public int someCounter = 0;
public class ABar {
public int i = 0;
public void someMethod(){
i++;
someCounter++;
}
}
public class BBar {
public void anotherMethod(){
bbar.someMethod();
someCounter++;
}
}
}
// then called using: //
Foo myFoo = new Foo();
myFoo.bbar.anotherMethod();
Edit
Seems the code I typed would have worked if i'd have tried it first; was trying to get help without being too specific. The code I'm actually having trouble with
Fails because of the error 'cannot make static reference to the non-static field stage'
public class Engine {
public Stage stage = new Stage();
// ...
public class Renderer implements GLSurfaceView.Renderer {
// ...
#Override
public void onDrawFrame(GL10 gl) {
stage.alpha++;
}
}
public class Stage extends MovieClip {
public float alpha = 0f;
}
In your code, yes, it is possible.
Non-static nested classes (inner classes) have access to other members
of the enclosing class, even if they are declared private. Static
nested classes do not have access to other members of the enclosing
class.
See: Nested Classes
If your inner class extends the outer class, then it will have access to the outer class public and protected members. I just tired it and it worked. The construct is a bit odd, because it implies a sort of infinite loop in the class definition, but it seems to do the job.
In my main class, I have an inner class called Shape which extends JButton. This inner class has a private char variable that goes by the name of CUBE.
I wrote getters and setters for it. I noticed that in the main method, instead of using:
(instance of Shape).getCUBE();
I can access it by using:
(instance of Shape).CUBE
Does this happen because CUBE is ultimately in the same class as main?
Is it necessary by java programming conventions that I write getters and setters for such an inner class?
Does this happen because CUBE is ultimately in the same class as main?
No, it works because the language specification says it does. It will end up as a separate class as far as the JVM is concerned, but extra package-level methods will be created to allow the outer class to appear to violate the normal rules.
The relevant section of the language specification is in 6.6.1:
Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (ยง7.6) that encloses the declaration of the member or constructor.
(Emphasis mine.)
So actually, even peer nested classes have access to private members. Sample code:
public class Test {
public static void main(String[] args) {
First first = new First(10);
Second second = new Second(first);
System.out.println(second.getValueFromFirst());
}
private static class First {
private final int value;
private First(int value) {
this.value = value;
}
}
private static class Second {
private final First first;
private Second(First first) {
this.first = first;
}
private int getValueFromFirst() {
return first.value;
}
}
}
If you look at the generated classes (with javap -c Test$First and javap -c Test$Second you'll see the synthetic methods generated by the compiler.
This is a class to mimic your description:
import javax.swing.JButton;
class Main
{
public class Shape extends JButton
{
private char CUBE = 'I';
public char getCUBE()
{
return CUBE;
}
public void setCUBE(char CUBE){this.CUBE = CUBE;}
}
public static void main(String[] args)
{
Shape sp = new Main().new Shape();
System.out.println(sp.CUBE);
System.out.println(sp.getCUBE());
}
}
public class TestMain
{
public static void main(String[] args)
{
Main.Shape sp = new Main().new Shape();
//System.out.println(sp.CUBE);
System.out.println(sp.getCUBE());
}
}
If you remove the comment, it won't compile. Therefore, if you want to access CUBE outside Main, you still need getter and setter.
That works because you forgot to add the private keyword.
I am trying to understand my way around polymorphism in Java. I created a parent class that has too many common methods that all children will use in the same manner.
Each of the subclasses' children all share static information, These variables or information will be used in the methods declared only in the parent.
The problem wish accessing static variables from Parent methods seems not really possible,
Its a solution to declare the common information per instance but since there will be 1000s of instances its such a waste of memory.
A simple elaboration of what i mean is the following code :
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
static
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
static
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
the output i expect was
1
2
1.
but what happens is :
1
2
2
One might think that on the initiation of each subclass the static variables of this subclass is set and then all methods referring to this subclass has access to the corresponding 'k' value.
But what actually happens is that all subclasses edit in the same static variable that is shared along all subclasses and hence destroys my whole point of using static variables for each subclass and its instances and using commmon methods in the Parent accessing these variables.
Any idea how can this be done ?
An option is to access the subclasses' static data through an abstract (non-static) method:
abstract public class Parent {
protected abstract int getK();
public void print() {
System.out.println(getK());
}
}
public class Child1 extends Parent {
private static final int CHILD1_K = 1;
protected int getK() { return CHILD1_K; }
}
public class Child2 extends Parent {
private static final int CHILD2_K = 2;
protected int getK() { return CHILD2_K; }
}
When you make new testChild2().print(); the static block on testChield2 was executed and change the value to 2.
static blocks only execute once when loaded by the ClassLoader.
This one give the output you want:
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Non static code blocks execute everytime the class is instanciated.
Premature optimization is the root of all evil. I don't think you'll run into any memory issues with thousands of instances, each with their own data, unless you're working on a tiny embedded system of some kind. Static variables are not intended to do what you're trying to do with them.
Static variables are specific to the class itself. If you want the same field in different instances of a class to have different values, then that field cannot be static.
The solution: don't make k static.
class testParent {
int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
this.k =2;
}
}
class testChild1 extends testParent{
{
this.k = 1;
}
public static void main(String[] args){
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Demo
(ignore the static class business - that's just to make it work in ideone).