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.
Related
I want to call this.getClass() before calling the constructor with super(...).
abstract class A extends SuperClass {
public A() {
super(Manager.someOtherMethod(this.getClass()))
// Does not work: "Cannot reference 'Object.getClass()' before
// supertype constructor has been called".
}
}
I read about a workaround using static methods, but this.getClass() cannot be called from a static context.
This question depends on my previous question.
Thanks in advance for you answers :)
Whilst I am dubious about the need for this, you can do it by inserting the call to Manager.someOtherMethod into the constructor of the superclass:
class SuperClass {
SuperClass() {
Object result = Manager.someOtherMethod(this.getClass());
}
}
class A extends SuperClass {}
class Manager {
static Object someOtherMethod(Class<?> clazz) {
System.out.println(clazz);
return new Object();
}
}
would print out
class A
(if you create an instance of A)
Ideone demo
If SuperClass has multiple constructors, you can assign the result to a field in the superclass:
class SuperClass {
private final Object result = Manager.someOtherMethod(this.getClass());
SuperClass() { ... }
SuperClass(String someParameter) { ... }
}
then result will be available in both constructors.
I suggest you to refactor your code.
I assume that you have classes A1, A2 and A3 now.
You should introduce factory like this:
class AFactory {
public static A1 newA1() {return new A1(A1.class);}
public static A2 newA2() {return new A2(A2.class);}
public static A3 newA3() {return new A3(A3.class);}
}
Add parameter to classes A1, A2 and A3 constructors.
Add parameter to A constructor.
...what's the question? Do I understood correctly, do you want the class to be subclassed, and THAT class should be given to the super, but you don't want to call super in all the subclasses?
Indeed it can't be done this way as the class object is not constructed yet, and therefore it does not exist. So you cannot call a method on the object yet, or ask for the name, or whatsoever.
I think you're stuck with either a class passing on to super, or add a pretty useless public static class<? extends SuperClass> getThisClass() { ... } or am I missing something nice? if I do, pls comment, as I actually like to know myself too.
Just for curiousity I tried different ways which are stated here: Getting the class name from a static method in Java but the closest I got was getting that class test.staticgetclass.A in the middle class, but never its subclass name which I think you want to get.
Use a class literal as a constructor parameter
abstract class A extends SuperClass {
protected A(Class<? extends A> clazz) {
super(Manager.someOtherMethod(clazz));
}
Then in impl:
class B extends A {
public B() {
super(B.class);
}
What I'm trying to do is instantiate an object in the parent class called "pObject" (assume the type to be protected Boolean). One child class which extends the parent class sets "object" to "true". The other child class which also extends the parent class will check to see if "object" is set to true.
Is this possible in Java?
public abstract class parentClassAction{
protected Boolean pObject;
}
public class childClass1Action extends parentClassAction{
super.pObject = true;
}
public class childClass2Action extends parentClassAction{
if(super.pObject!=null){
if(super.pObject == true){
System.out.println("Success");
}
}
}
You can make pObject static and access it as parentClassAction.pObject.
If you have 2 different instances of subclasses - they do not share any state. Each of them has independent instance of pObject, so if you change one object it will not be seen in another one.
There are many ways to solve your problem. The easiest way: you can make this field pObject to be static - it will work for simple example, but this can be also serious limitation (if you want to have more than one instance of pObject).
Yes. If pObject is static it will be shared:
public class Legit {
public static abstract class A {
protected static Boolean flag;
}
public static class B extends A {
public void setFlag(boolean flag) {
super.flag = flag;
}
}
public static class C extends A {
public boolean getFlag() {
return super.flag;
}
}
public static void main (String [] args) {
B b = new B();
C c = new C();
b.setFlag(true);
System.out.println(c.getFlag());
b.setFlag(false);
System.out.println(c.getFlag());
}
}
You can access non private fields of a super class using the syntax:
super.myBoolean = true;
Note: If the field has the default visibility (absence of modifier) it is accessible only if the sub class is in the same package.
Edited: I add information due to the new code added to the question.
It seems that you like to check a variable from two different objects. It is possible only if that variable is static. So declare it as protected static in the parent class. The rest of code rest the same.
I have a class A with static field F:
class A {
public static String F = null;
}
Class B:
class B extends A {
public static String F = "somestring";
}
and a typed class with a method that uses field F:
class C<T extends A> {
public void someMethod() {
String someString = T.F;
// Manipulations with someString
}
}
And then my code that calls it.
C<B> c = new C<B>();
c.someMethod();
and I'm getting a null pointer exception when trying to manipulate with someString. So, the T.F is null, but T is B, so it should be "somestring"! Why?
You can't Override fields. Since it is extends A, it will always use the field in A.
Add a getter in class A and B that returns F. From there, Override the method in A with the one in B.
class A {
public String getF(){
return null;
}
}
class B {
#Override
public String getF(){
return "someString";
}
}
This doesn't have to do with generics.
The fields of a class cannot be overridden by a subclass - only methods can. So, even if you define a field in your subclass with the same name as the one in the superclass, you're merely creating a new field that simply happens to have the same name but actually shadows (not overrides) the previous one.
Consider putting an assignment with the default value of the field in the constructor of your subclass. Then it should work.
A static member in Java can be hidden, but not overridden. A reference to a static member is resolved at compile time - and at compile time, the only known type of T is A.
See http://www.coderanch.com/how-to/java/OverridingVsHiding.
Edit: A field cannot be overridden anyway, whether it is static or instance.
This happens because all the static members of A are common to A alone and cannot be inherited by B.
No new static member, which is not present in A, can be present in B.
Virtually, when you say
class C < T extends A > {
...
}
You can only use methods(both static and instance - unless #Overriden) and fields which are common in A. So, since F is not an instance field, it is not overriden and the JVM finds the occurance of F in A.
Hence you get an NPE.
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
}
}
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.