Pass a class variable to another class - java

I'd like to pass a class variable to another class and make it a class variable of that class. How would I do this in the following context?
public class GLCamTest extends Activity {
public float array[] = something;
}
class GLLayer extends GLSurfaceView implements SurfaceHolder.Callback,
Camera.PreviewCallback, Renderer {
//Get class variable here
}

It is difficult to understand wjat you are asking, but here's a possible answer:
Make class B a subclass of A:
public class A {
// Declaration of the 'array' attribute
public float[] array = new float[]{1.1f, 2.2f, 3.3f};
}
class B extends A {
// Every instance of 'B' also has an 'array' attribute
}
If array is redeclared to be public static, you get a situation where there is an array attribute that can be referred to as A.array or B.array. (Or within either A or B as just array ... or even as a.array or b.array where a and b have types A and B respectively.)
If you cannot create a direct or subtype relationship between A and B (or A, B and some third class containing the declarations) then you are out of luck. There is no way that they can share declarations.
However, you can use static imports to make it seem like the declaration is shared. For example:
public class A {
// Declaration of the 'array' attribute
public float[] array = new float[]{1.1f, 2.2f, 3.3f};
}
import static A.array;
class B {
// now I can use 'array' without qualifying it with 'A'
}
Incidentally, it is generally a bad idea to use static variables to share state, especially state represented as bare arrays. This is distinctly non-object-oriented.

Do you have access to instance of A? Or maybe you want array to be static?

Do you want the array to be visible everywhere (as if it was a global variable)?
If so then it needs to be static.
But my guess is that you want to pass an instance of GLCamTest on to a GLLayer object, in which case you should use a setter function or pass it in the constructor.
public class GLCamTest extends Activity {
public float array[] = something;
}
class GLLayer extends GLSurfaceView implements SurfaceHolder.Callback,
Camera.PreviewCallback, Renderer {
private GLCamTest camTest;
public void setCamTest(GLCamTest camTest) {
this.camTest = camTest;
// Now you can access the array using camTest.array
}
}

Related

Scope Issue. How to reference method?

I have this scenario:
public class A
{
private final Integer index;
public Integer getIndex() { return index; }
public static class B
{
//unimportant
}
}
public class C extends B
{
//how to reference getIndex() here?
}
How can I call getIndex() in class C's body?
Odd scenario... but you'd have to move class C to also be an inner class inside class A. Shrug? Curious why are you extending an inner class in the first place? What are the restrictions of the design that are causing this? Not judging you at all. Having the thinking behind the design could aide in possibly finding an alternative solution.
public class A
{
// make sure final value is set here or in constructor
private final Integer index = 0;
public Integer getIndex() { return index; }
public static class B
{
//unimportant
}
//Doesn't make much sense... but...
public class C extends B
{
//can now call getIndex()
public void callGetIndex() {
getIndex();
}
}
}
Bonus research:
For those that are maybe as curious as me and thought about using this to reference the function from another file. If you compile C in another file, and try accessing getIndex by using the enclosing this:
A.this.getIndex();
Sadly that won't work because even though C extends B, it still needs to be enclosed by A for that methodology to work. You get this compile time error:
C.java:5: error: not an enclosing class: A
A.this.getIndex();
^
1 error
Hey cool! another answer, based off #mzl's answer below:
So interestingly enough, You can keep B static and extend both classes to get what you want to do. This is useful for example if you can not edit file A.java, because A.java is 3rd party functionality. (give #mzl credit here for his answer below)
Here is how you'd do it that way! ( Tested this compiles via javac A.java C.java )
A.java
public class A
{
private final Integer index = 0;
public Integer getIndex() { return index; }
public static class B
{
//unimportant
}
}
C.java
public class C extends A
{
public class D extends A.B {
//can now call getIndex()
public void callGetIndex() {
getIndex();
}
}
}
I've created a static over flow project proving #mzl's theory here:
https://github.com/davethomas11/stackoverflow_Q_39441077
One gothcha. You'll notice I create an instance of C before D to make sure there is access to getIndex(). I haven't tested what happens if you instantiate D directly I will do that later and post the results.
Late update on that instantiate D directly test.
I added C.D testD = new C.D(); in my static main function:
$ sh build.sh
StackOverflowQuestion39441077.java:5: error: an enclosing instance that contains C.D is required
C.D testD = new C.D();
^
1 error
The compiler helps us by not letting us do this.
If you want to extend (non-statically) a inner class you must extend the outer class aswell.
You could do it this way:
public class A
{
private final Integer index;
public Integer getIndex() { return index; }
public static class B {}
}
public class D extends A{
public class C extends B{}
}
You can't. C extends B which does not have a getIndex() method. C must extend A to inherit that method.
(I feel it is an interesting theoretical question but with little meaning in practice.)
You can't event access A.getIndex from B because B is static, and getIndex is not, so to invoke getIndex you need a non-null instance of A.
Assuming you could make B non-static, you couldn't either, because your scheme becomes contradictory:
In one hand, class B is inner, so to instantiate a new object a previous non-null instance of A is required:
A a=new A();
B b=a.new B();
But in the other hand, class C is a top-level (not inner) class, so it may be directly instantiated. However, being a subclass of B, it is subject to the same restrictions as its superclass: It needs an instance of A. Contradictory!
The only way I think to make it work is to declare getIndex static, so no instance of A would be needed (in fact, neither subclassing from B would be a problem).

Java transferring variables from a super class to the sub class

In java i have a class A which extends class B
I want to assign all of the contents from class B to class A
thing is i want to do it from inside class A now this seems reasonable easy to do just transfer all of the variables.
This is the hard part. I didn't make class B it's a part of android.widget
In c++ you would just take in class b and then assign to *this and cast it.
How would i go about doing this in java?
To further clarify it's a relativelayout i need to copy all the contents of a relativelayout into a class that extends relative layout
class something extends other
{
public something(other a){
//transfer all of the other class into something
this=(something)a; // obviously doesn't work
//*this doesn't exist?
//too many variables to transfer manually
}
}
Thanks so much for all the help. Really appreciate it!!!
See the code given below . It is using java.lang.reflect package to extract out all the fields from super class and assigning the obtained value to the child class variables.
import java.lang.reflect.Field;
class Super
{
public int a ;
public String name;
Super(){}
Super(int a, String name)
{
this.a = a;
this.name = name;
}
}
class Child extends Super
{
public Child(Super other)
{
try{
Class clazz = Super.class;
Field[] fields = clazz.getFields();//Gives all declared public fields and inherited public fields of Super class
for ( Field field : fields )
{
Class type = field.getType();
Object obj = field.get(other);
this.getClass().getField(field.getName()).set(this,obj);
}
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
Super ss = new Super(19,"Michael");
Child ch = new Child(ss);
System.out.println("ch.a="+ch.a+" , ch.name="+ch.name);
}
}
All the variable and function of parent class(not private) is direct access in child class.You don't need to assign any thing in child Class.You can direct access.
This will not work:
Something something = (Something) other.clone();
if the true runtime type of other is Other.
Instead you have to create a copy constructor, or instantiate other as an instance of Something and then clone it.

Java - using the 'super' keyword

Simple question. I made a class called Tester1 which extends another called Tester2. Tester2 contains a public string called 'ABC'.
Here is Tester1:
public class Tester1 extends Tester2
{
public Tester1()
{
ABC = "Hello";
}
}
If I instead change line 5 to
super.ABC = "Hello";
am I still doing the exact same thing?
Yes. There's only one ABC variable within your object. But please don't make fields public in the first place. Fields should pretty much always be private.
If you declared a variable ABC within Tester1 as well, then there'd be a difference - the field in Tester1 would hide the field in Tester2, but using super you'd still be referring to the field within Tester2. But don't do that, either - hiding variables is a really quick way to make code unmaintainable.
Sample code:
// Please don't write code like this. It's horrible.
class Super {
public int x;
}
class Sub extends Super {
public int x;
public Sub() {
x = 10;
super.x = 5;
}
}
public class Test {
public static void main(String[] args) {
Sub sub = new Sub();
Super sup = sub;
System.out.println(sub.x); // Prints 10
System.out.println(sup.x); // Prints 5
}
}
Yes, the super qualifier is unnecessary but works the same. To clarify:
public static class Fruit {
protected String color;
protected static int count;
}
public static class Apple extends Fruit {
public Apple() {
color = "red";
super.color = "red"; // Works the same
count++;
super.count++; // Works the same
}
}
Well first thing is that the variable ABC must be declared in the class Tester2. If it is then yes you are.
You are. Given that ABC is visible to Tester1 (the child class), it is assumed to be declared anything but private and that is why it is visible to a sub-class. In this case, using super.ABC is simply reinforcing the fact that the variable is defined in the parent.
If, on the other hand, ABC had been marked private in the parent class, there would be no way of accessing that variable from a child class - even if super is used (without using some fancy reflection, of course).
Another thing to note, is that if the variable had been defined private in the parent class, you could define a variable with the exact same name in the child class. But again, super would not grant you access to the parent variable.

Java Class inheritance: can I make non static member in the parent class become static in the son?

Before you start reading I would like to clarify:
I have already thought of other designs and work arounds
I'm only interested in the problem I exposed and not "changing" it (so no solutions such as delete the points in A and create new points fields in B and C...
lets consider the following code:
public class A {
protected cpVect[][] points = null;
...
}
and its classes that inherits it:
public class B extends A{
...
}
public class C extends A{
...
}
so far so good.
my problem is that for B and C contains arrays of points that will be created in the constructor using something like
if(points == null){calculate points code}
the problem is as follow
points in A can't be static because the dimensions are different in B and C.
but every instance of B will share the B points and every instance of C will share the C points. (in other words a Square will always be a square and a triangle will always be a triangle). and therefore I want to have the B:points and C:points static so that i don't get duplicates of the values for every instance.
So is there a way to redefine points as static in B and C when it is not static in A?
If you access points solely through property methods (getters/setters) you can do whatever you want in the subclasses. If you use inheritance, A will have to be an abstract class. Otherwise you'd always carry around the empty points variable in A (losing 8 bytes, probably).
In this case the hierarchy would look like this:
abstract class A {
abstract public cpVect[][] getPoints();
// more methods ...
}
public class B extends A {
private final static cpVect[][] POINTS = calculatePoints();
#Override
public cpVect[][] getPoints() {
return POINTS;
}
private cpVect[][] calculatePoints() {
// ...
}
}
And the same for C. If A includes no other state or functionality, you should make it an interface.
You can't make the field static, but you could make it a singleton. You'll have multiple references to the singleton, but you'll only need one copy of each points array. For example, in B:
class B extends A {
private cpVect[][] B_points = null;
public B() {
if (B_points == null)
B_points = create_B_points();
points = B_points;
}
}
If multithreaded, you'll need to add synchronization.
(Sorry for earlier half-finished version. The SO editor seems quirky in Chrome).
There is no significance of static and non-static in inheritance. ie if you have a member variable in a parent class then you can have the same name for the static member of the child class. as shown
class test {
public int a;
}
class test1 extends test {
public static int a;
}
And through objects you can access a of test.
through class test1 you can access static a of test1. as both are independent.
You cannot have a same variable as the member in parent and static in child.

Overriding a super class's instance variables

Why are we not able to override an instance variable of a super class in a subclass?
He perhaps meant to try and override the value used to initialize the variable.
For example,
Instead of this (which is illegal)
public abstract class A {
String help = "**no help defined -- somebody should change that***";
// ...
}
// ...
public class B extends A {
// ILLEGAL
#Override
String help = "some fancy help message for B";
// ...
}
One should do
public abstract class A {
public String getHelp() {
return "**no help defined -- somebody should change that***";
}
// ...
}
// ...
public class B extends A {
#Override
public String getHelp() {
return "some fancy help message for B";
// ...
}
Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).
Because you can only override behavior and not structure. Structure is set in stone once an object has been created and memory has been allocated for it. Of course this is usually true in statically typed languages.
Variables aren't accessed polymorphically. What would you want to do with this that you can't do with a protected variable? (Not that I encourage using non-private mutable variables at all, personally.)
class Dad{
public String name = "Dad";
}
class Son extends Dad{
public String name = "Son";
public String getName(){
return this.name;
}
}
From main() method if you call
new Son().getName();
will return "Son"
This is how you can override the variable of super class.
Do you mean with overriding you want to change the datatype for example?
What do you do with this expression
public class A {
protected int mIndex;
public void counter(){
mIndex++;
}
}
public class B extends A {
protected String mIndex; // Or what you mean with overloading
}
How do you want to change the mIndex++ expression without operator overloading or something like this.
If you have the need to override an instance variable, you are almost certainly inheriting from the worng class.
In some languages you can hide the instance variable by supplying a new one:
class A has variable V1 of type X;
class B inherits from A, but reintroduces V1 of type Y.
The methods of class A can still access the original V1. The methods of class B can access the new V1. And if they want to access the original, they can cast themself to class A (As you see dirty programming provokes more dirty progrtamming).
The best solution is to find another name for the variable.
you can override a method,that is all right
but what do you mean by overriding a variable?
if you want to use a variable at any other place rather than super class
u can use super.
as in
super(variable names);
why do you want to override a variable?
i mean is there any need?
we can not overriding structure of instance variables ,but we ovverride their behavior:-
class A
{
int x = 5;
}
class B extends A
{
int x = 7:
}
class Main
{
public static void main(String dh[])
{
A obj = new B();
System.out.println(obj.x);
}
}
in this case output is 5.

Categories

Resources