I have an array named Floors in class A, it contains values something like the following:
List<Point> manualpoint = new ArrayList<Point>();
int[] manualpointx = {135,200,300,155,235,300};
Let's say I wish to pass these values to class B, supposingly class B has already declared a superclass View
public class DrawView extends View implements OnTouchListener {
#Override
public void onDraw(Canvas canvas) {
//pass the values into this class
}
}
How do i pass the values from class A to B?
To pass data between activities
//to pass array use
intent.putExtra("intarray", manualpointx);
// to pass list of point use
intent.putParcelableArrayListExtra("bundle", (ArrayList<? extends Parcelable>) manualpoint);
For classes
create public getter methods to return the values and call those
methods from any class where you want to get the values
You can do something like this.
final class A
{
private static int[] manualpointx = {135,200,300,155,235,300};
private static List<Point> manualpoint = new ArrayList<Point>();
public static int[] returnArray()
{
return(manualpointx);
}
public static List<Point> returnList()
{
return(manualpoint);
}
}
public class DrawView extends View implements OnTouchListener
{
#Override
public void onDraw(Canvas canvas)
{
//pass the values into this class
int arr[]=A.returnArray();
List<Point> list=A.returnList();
}
}
If you need only non-static fields in your class A and if you just want to use non-static methods, you will have to access them via an instance of the class A from your class DrawView.
You need to create an instance of Class A and then access the values from Class B, for example:
public class ClassA {
private int someInt;
public ClassA() {
someInt = 5;
}
public int getSomeInt() {
return someInt;
}
}
public class ClassB {
public void someMethod() {
ClassA instanceOfClassA = new ClassA();
int someIntFromClassA = instanceOfClassA.getSomeInt(); //This is now 5;
// Rest of your code here
}
}
Alternatively you can create it as a static method in ClassA and then call it in ClassB by using ClassA.getSomeInt();
Another one idea is , try having a public class in B and if possible call the B's set Array method with the Array values of A. now in set Array we can have a class variable to save the Array values and then call draw.
public class DrawView extends View implements OnTouchListener {
int[] manualpointx;
setArray(int[] manualpointx1){
this.manualpointx = manualpointx1
}
public void onDraw(Canvas canvas) {
//pass the values into this class
we can use manualpointx
}
}
Related
public class MyTest {
public static void main(final String[] args) {
B b = new B();
b.print();
}
}
class A {
private final int x = 5;
protected int getX() {
return x;
}
public void print() {
System.out.println(getX());
}
}
class B extends A {
private final int x = 10;
#Override
protected int getX() {
return x;
}
}
In this example, I need to print subclass value in the parent class.
It is working fine. No issue.
Now it is printing 10.
But I do not want to define that property in the parent class A.
Because in this example this x datatype is very simple. So no issue.
But in real-time I want to use other datatype which may be another Class variable or List<something> which have huge data.
So ultimately I do not wish to store that value in Class A.
Because it is redundant data. It will slow down in my Hibernate thing.
Please let me know, how to achieve this without declaring variable in parent class. But I still need to use subclass variable in parent class.
make abstract your class A and the getX(); method.
public class Test {
public static void main(final String[] args) {
B b = new B();
b.print();
}
}
abstract class A {
protected abstract int getX();
public void print() {
System.out.println(getX());
}
}
class B extends A {
private final int x = 10;
#Override
protected int getX() {
return x;
}
}
and override the toString method in place of your print method
#Override
public String toString() {
return String.valueOf(getX());
}
the final code
public class Test {
public static void main(final String[] args) {
B b = new B();
System.out.println(b);
}
}
abstract class A {
protected abstract int getX();
#Override
public String toString() {
return String.valueOf(getX());
}
}
class B extends A {
private static final int X = 10;
#Override
protected int getX() {
return X;
}
}
you could also define as static your x variable
But as say Andrew Tobilko you can consider also to use an interface if A doesn't represent a stateful entity.
It's certainly the best solution for your case, mix the use of an interface and an abstract class
public class Test {
public static void main(final String[] args) {
B b = new B();
System.out.println(b);
}
}
interface MyInterface {
int getX();
}
abstract class A implements MyInterface{
#Override
public String toString() {
return String.valueOf(getX());
}
}
class B extends A {
private static final int X = 10;
#Override
public int getX() {
return X;
}
}
You need the getX within the parent class, but you don't have information enough to implement this method there.
You can declare this class as abstract and mark the method with abstract as well. Doing that, you are handing the responsibility of method implementation over its subclasses and preventing from parent field declaration.
If the A doesn't describe any state (only actions/methods), you should consider replacing it with an interface. At the current state, it is the case.
You could make the parent class abstract, eliminate the property in the parent class, make getX() abstract, and then leave print() as concrete. Then just use the concrete implementation of getX() in the child class.
I have an issue:
There are 2 classes that implements some interfaces. In class A I have a list of objects of class B.
Is there exist a way to populate these list using class B constructor instead of hardcode every object that will be created?
In class A I have method that search for particular class B object by given parameter, but the problem is to figure out how to "autopopulate" this list every time the new object is created.
I Was trying to invoke method addNodeToList() form class A, but witout an instance of this class I cant do that.
Is there any elegant way to autopopulate this list?
here is the code:
CLASS A
public class MyStructure implements IMyStructure {
private List<INode> nodes;
public MyStructure() {
}
#Override
public INode findByCode(String code) {
//impl
}
#Override
public INode findByRenderer(String renderer) {
//impl
}
#Override
public int count() {{
//impl
}
public void addNodeToList(INode node){
nodes.add(node);
}
}
CLASS B
public class CompositeNode implements ICompositeNode {
private String code;
private String renderer;
MyStructure myStructure;
public static int counter;
public CompositeNode(String code, String renderer){
this.code= code;
this.renderer=renderer;
myStructure.addNodeToList(this);
counter++;
}
EDIT:
I was thinking about create static list inside of class B, but I think it is not a good practice.
I am out of idea how to solve this the efficent way.
FINISHED:
I have created a method Inside of class A like this:
public class MyStructure implements IMyStructure {
public void addNodeToList(String code, String renderer) {
CompositeNode node = new CompositeNode(code, renderer);
nodes.add(node);
}
It works the way I wanted - I dont store the list inside of class B and it populate the list it self.
Without knowing further context and usage I would simply add a getter in class A:
public class MyStructure implements IMyStructure {
//...
public List<INode> getNodes() {
return this.nodes;
}
//..
}
and then it can be used in class B to add an element to the list of class A:
public CompositeNode(String code, String renderer){
//...
myStructure.getNodes.add(this);
//...
}
I don't think you need the addNodeToList method, unless used elsewhere.
You can instantiate the list of INode objects and add the first node in the MyStructure's constructor so you can create CompositeNode with MyStructure object filled with CompositeNode object in this way:
MyStructure
public class MyStructure implements IMyStructure {
private List<INode> nodes;
public MyStructure() {
super();
}
public MyStructure(INode node) {
nodes = new ArrayList<>();
nodes.add(node);
}
//...
}
CompositeNode
public class CompositeNode implements ICompositeNode {
private String code;
private String renderer;
private MyStructure myStructure;
public static int counter;
public CompositeNode(String code, String renderer){
this.code= code;
this.renderer=renderer;
myStructure = new MyStructure(this);
counter++;
}
//...
}
//Class defined in external jar
class A{
many methods...
public getId() {};
}
//I want to extends this class and overwrite single method
class MyA extends A{
private int myId;
public getId() {return myId};
}
void main ()
{
A a = Factory.getA(); //External class create the instance
MyA mya = (MyA)a; //runtime Error!! I want to convert A to myA
}
Hi,
I want to extends an instance which I get from external Jar and overwrite a single method getId(). I don't control the creation of the instance so the only solution I got was to pass it to my constructor and init all members manually, example here:
class MyA extends A{
private int myId;
public MyA(A a, int myId)
{
this.myId = myId;
//init all other methods from a.? to this.?
this.setXXX(a.getXXX());
this.setYYY(a.getYYY());
....many methods...
}
public getId() {return myId};
}
Is there a better way?
MyA mya = (MyA)a; //runtime Error!! I want to convert A to myA
Is a an instance of MyA?? You can not convert if it is not an instance of MyA. you get java.lang.ClassCastException.
Rather than getting all data from A in the constructor of MyA (and thus reimplementing it completely), create an Adapter, change the methods you need and in the rest just pass the calls to the original instance of A:
class MyA extends A{
private A adaptee;
private int myId;
public MyA(A adaptee, int myId)
{
this.adaptee = adaptee;
this.myId = myId;
}
// Override the method you need to
#Override
public getId() {return myId};
...
// Override the rest of the methods so they call the adaptee.
#Override
public X getXXX() {
return a.getXXX();
}
#Override
public void setXXX(X x) {
a.setXXX(x);
}
...
}
Then, of course, use it as:
A a = new MyA(Factory.getA(), myId);
... a.getId();
Is it possible to create an array of static classes in Java?
For example:
SceneObject[] scenes = {Loading.class, Menu.class};
// Loading and Menu extend SceneObject
We need to call static methods via the array, not instantiate them.
EDIT:
The following is what we are trying to accomplish. We could alternatively use many switches, but it sounds redundant to add every object to every switch in every method.
package net.bitworm.gameengine;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import net.bitworm.scenes.*;
public class SceneController {
public enum Scene{
LOADING_SCENE,
MENU,
SCENE_1
}
public static SceneObject[] scenes = {new Loading(), new Menu()};
public volatile static Scene currentScene = Scene.LOADING_SCENE;
public static void setScene(Scene newScene){
currentScene = newScene;
System.out.println("Switched to " + currentScene.toString());
}
public static void update(GameContainer container, int delta){
scenes[currentScene.ordinal()].update(container, delta);
}
public static void render(GameContainer container, Graphics g){
scenes[currentScene.ordinal()].render(container, g);
}
public static void mouseMoved(int oldx, int oldy, int newx, int newy){
scenes[currentScene.ordinal()].mouseMoved(oldx, oldy, newx, newy);
}
public static void mousePressed(int button, int x, int y){
scenes[currentScene.ordinal()].mousePressed(button, x, y);;
}
public static void mouseReleased(int button, int x, int y){
scenes[currentScene.ordinal()].mouseReleased(button, x, y);
}
public static void mouseWheelMoved(int change){
scenes[currentScene.ordinal()].mouseWheelMoved(change);
}
public static void keyPressed(int key, char c){
scenes[currentScene.ordinal()].keyPressed(key, c);
}
public static void keyReleased(int key, char c){
scenes[currentScene.ordinal()].keyReleased(key, c);
}
You need to differentiate between classes and objects. For example, you might have:
SceneObject[] scenes = { new Loading(), new Menu() };
or
Class[] classes = { Loading.class, Menu.class };
It's not clear from your question which you mean, but hopefully that should satisfy either case... note that you can't have generic arrays, so with the Class[] you can't specify that each class must extend SceneObject.
EDIT: Now we've got a bit more information, it sounds like you've got this:
abstract class SceneObject {}
class Menu extends SceneObject {
static void foo() {
}
static void bar() {
}
}
class Loading extends SceneObject {
static void foo() {
}
static void bar() {
}
}
The two foo methods here are completely unrelated - you can't use polymorphism to call them, because they're static methods. If you want to use polymorphism - i.e. call a method knowing which signature you want to call, but with an implementation that depends on the target of the call - you need instance methods:
abstract class SceneObject {
abstract void foo() {
}
abstract void foo() {
}
}
class Menu extends SceneObject {
#Override void foo() {
}
#Override void bar() {
}
}
class Loading extends SceneObject {
#Override void foo() {
}
#Override void bar() {
}
}
Then you can write:
SceneObject[] scenes = { new Loading(), new Menu() };
...
for (SceneObject scene : scenes) {
scene.foo();
scene.bar();
}
Other than making an array of classes that extend SceneObject, we can make a container for these objects:
//a container that holds only the classes of SceneObject
public class ClassBox<T extends SceneObject> {
private Class<T> theClass;
public ClassBox(Class<T> theClass) {
this.theClass = theClass;
}
public Class getTheClass() { //'getClass()' method is reserved, we use a more unique name
return theClass;
}
}
//testing classes
abstract class SceneObject {}
class Loading extends SceneObject {}
class Menu extends SceneObject {}
class noExtends1 {}
//testing
public void main() {
ClassBox[] scenes = {new ClassBox<>(Loading.class), new ClassBox<>(Menu.class)}; //these classes extend SceneObject
// ClassBox[] sceneserror = {new ClassBox<>(Loading.class), new ClassBox<>(noExtends1.class)}; //gives error because 2nd array elem is not extending, so I commented it
Log.v("custom log.v call", String.valueOf(Loading.class));
Log.v("custom log.v call", String.valueOf(Menu.class));
Log.v("custom log.v call", String.valueOf(scenes[0].getTheClass()));
Log.v("custom log.v call", String.valueOf(scenes[1].getTheClass()));
//result is:
//V/custom log.v call: class me2.iwanttobealeader.pie$Loading
//V/custom log.v call: class me2.iwanttobealeader.pie$Menu
//V/custom log.v call: class me2.iwanttobealeader.pie$Loading
//V/custom log.v call: class me2.iwanttobealeader.pie$Menu
}
This answer has the benefit of specifying multiple criteria of inheritance for example:
public class ClassBox<T extends Fragment & FR_DbRequests.SynchListener>
//now it must implement the abstract class SyncListener and extend Fragment
But also the disadvantage of instantiating an additional object ,namely the container+variable containing the class, instead of just the variable containing the class.
I also done this example creating object for both class and call the method is there anyway to override the baseclass?
class Car {
void Max() {
System.out.println("Audi");
}
}
class Speed extends Car {
void Max() {
System.out.println("300");
}
public static void main(String args[]) {
Speed s=new Speed();
s.Max();
}
}
At the risk of being called a "give me the repz" type person...hopefully this helps:
This first class is a BaseClass, you can create a new one by writing:
BaseClass myBaseClass = new BaseClass();
public class BaseClass {
private int aNumber; //This global variable is private and so cannot be overwritten.
int anotherNumber; //This global variable is package scope and so can be accessed by sub-classes in the same package.
protected yetAnotherNumber; //This variable is accessible by any subclasses.
public int numberAvailableToEveryone; //This global variable is accessible to anyone and everyone.
public BaseClass() {} //This is a constructor (no return type)
private void myPrivateMethod() {} //This method cannot be overwritten
void packageScopeMethod() {}
protected void thisMethodCanBeOverwrittenBySubClasses() {}
public void theWorldCanCallMe() {} //extendable to the world, not much different than protected scope tbh
}
Now, to overwrite a method you can create an anonymous class like so:
BaseClass myAnonymousClass = new BaseClass() {
public void theWorldCanCallMe() {
//in here you can override the method to do whatever you want.
}
}
or you could define a subclass like so:
public class SubClass extends BaseClass {
#Override
public void tehWorldCanCallMe() {
//again your new code goes here
}
}
and then instantiate it like so:
SubClass myClassThatOverridesAMethod = new SubClass();
A car example closer to your code:
class Car {
private String name;
int speed = 100;
Car(String name) { //This is the base classes constructor
this.name = name;
}
String max() {
return speed;
}
void run() {
System.out.println(name);
System.out.println(max()); //will print the base speed unless overridden
}
}
class Audi extends Car {
Audi() {
super("Audi")
}
}
class Speed extends Car {
Speed() {
super("Speed");
}
#Override
String max() {
speed = 300;
return speed;
}
public static void main(String args[]) {
Speed s=new Speed();
s.run();
}
}