What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways.
Let me try to illustrate a simplified version of my problem:
This was my code before:
public class Top_Level_Class(){
int x, y;
// gets user input which changes x, y;
public void main(){
int p, q, r, s;
// compute p, q, r, s
doA(p,q,r);
doB(q,r,s);
}
public void doA(int p, int q, int r){
// do something that requires x,y and p, q, r
}
public void doB(int q, int r, int s){
// does something else that requires x, y and q, r, s
}
}
Now it looks something like this:
public class Top_Level_Class(){
int x, y;
SomeClass1a a = new SomeClass1a();
SomeClass1a b = new SomeClass1b();
// gets user input which changes x, y;
public void main(){
int p, q, r, s;
// compute p, q, r, s
a.doA(p,q,r);
b.doB(q,r,s);
}
public class SomeClass1a() { // in its own separate file
public void doA(int p, int q, int r){
// do something that requires x,y and p, q, r
}
}
public class SomeClass1b() { // in its own separate file
public void doB(int q, int r, int s){
// does something else that requires x, y and q, r, s
}
}
So anyway, should I pass x and y each time (where x,y are variables stored in the helper class func) ?
a.set(x,y);
a.doA(p,q,r);
My idea was to have a special container class where x and y are held. The top level class would have an instance of the container class and change x,y using the set methods.
// in the top level class:
Container c = new Container(x,y);
a.setContainer(c);
b.setContainer(c);
My helper classes would also have an instance of the container and it would point to the same instance as in the top level. That way they access the same x,y as in the top level.
I would like to know if I should
Use the container class
Load x,y each time into the subclasses
?? Some better method ??
I guess the answer to your question is the Design Pattern called Singleton.
It basically allows you to get and exploits the same (and unique) instance of a class whenever you want in your system.
This is its implementation (please forgive possible syntax errors, I did not compile it):
class Container{
//eventually provides setters and getters
public float x;
public float y;
//------------
private static Container instance = null;
private void Container(){
}
public static Container getInstance(){
if(instance==null){
instance = new Container();
}
return instance;
}
}
then if elsewhere in your code you import the Container you can write for example
Container.getInstance().x = 3;
temp = Container.getInstance().x;
and you will affect the attributes of the unique container instance you have in your system
In many cases it is however better to use the Dependency Injection pattern as it reduces the coupling between different components.
I am having a hard time seeing what your problem is -- why don't you want to pass x an y as a parameter?
Oh, well. Assuming you don't, I don't see a need for a new container class. Do it this way:
public class SubClass1a() { // in its own separate file
public void doA(Top_Level_Class caller, int p, int q, int r){
// do something that requires x,y and p, q, r
// **to get x use the expression term caller.getX() and caller.getY()**
}
}
Of course you need to add the public getter methods getX() and getY() to Top_Level_Class.
If you do not want SubClass1a to be dependent on Top_Level_Class then you could create an interface that provides access to the variables.
Blockquote
The main reason I didn't want to pass x,y each time is because I have several functions in several SubClasses that each use (x,y, z, etc) and it didnt seem right to pass in like 6-8 variables each time I call a function. The sub classes used to be dependent, but I'm trying to take them out of the file so they can be used in a different project.
Blockquote
If this is the case then you are better off abstracting your variables out to a container class. If every instance of these no-longer-dependent classes is going to use a large subset of these variables then it makes sense to have them all in one instance. Variables that are logically related should be found in the same place. Your approach should be something like:
public class Top_Level_Class(){
Container container = new Container(x, y, p, q, r, s);
SubClass1a a = new SubClass1a(container);
SubClass1a b = new SubClass1b(container);
// gets user input which changes x, y using container's getters and setters
public void main(){
// compute and set p, q, r, s
a.doA();
b.doB();
}
public class SubClass1a(Container c) { // in its own separate file
public void doA(c.getX, c.getY, c.getP, c.getQ, c.getR){
// do something that requires x, y, p, q, and r
}
}
public class SubClass1b(Container c) { // in its own separate file
public void doB(c.getX, c.getY, c.getQ, c.getR, c.getS){
// does something else that requires x, y, q, r, and s
}
}
public class Container(x, y, p, q, r, s) {
//getters and setters for all variables
}
This keeps you from getting into a variable passing spaghetti-code situation, and when you want to use just one or two of these classes later your code is modular enough to port with just those classes and your container.
This question is a bit mad - the code in the question won't compile.
public class Main {
public static void main(String... args) {
MutableDataContainer m = new MutableDataContainer();
ImmutableDataContainer i = computeImmutableData();
new ADoer().doA(m, i);
new BDoer().doB(m, i);
}
...
}
class MutableDataContainer {
private int x, y;
... // getters and setters below
}
class ImmutableDataContainer {
private final int p, q, r, s;
... // getters below
}
You'll need to define ADoer and BDoer as well.
Related
I am not primarily a Java programmer... I would like to find a corresponding Java syntax for class storing a function pointer (templatized) as a variable. The function pointer points to a function "outside" the class. The original code is in C++11:
#include <memory>
template <typename T>
using p_function = T(*)(T, T, T);
template <typename T>
class A
{
private:
int k;
p_function<T> pf;
public:
A() { pf = NULL; k = 0; }
A(p_function<T> pf_, int k_) { pf = pf_; k = k_; }
T getF(const T a1, const T a2, const T a3) const { return pf(a1, a2, a3); }
};
template <typename T>
T f1(T x, T y, T z) { return x + y + z; }
template <typename T>
T f2(T x, T y, T z) { return x - y - z; }
int main()
{
A<double> aa (f1<double>, 1.0);
double val= aa.getF(1.0, 2.0, 3.0);
}
Thinking about the problem, is it reasonable to use the interface?
public interface Function <T> {
T pf(T x, T y, T z);
}
or, is there any better way? Java is relatively rapidly develops, there might be "straighter" constructions than few years ago. There are several requirements which I am not able to join together. Could I ask for a short code sample in Java? Thank you very much for your help.
Use java 8. That uses "functional" interfaces (indeed) where an interface defines just one single function.
To not overuse the existing Function class, introduce your own name.
#FunctionalInterface
public interface TriFunction<T> {
T apply(T x, T y, T z);
}
Marking it with the FunctionalInterface annotation is a practice that prevents adding a second function and such.
class Foo {
public static Bar hop(Bar x, Bar y, Bar z) { ... }
}
TriFunction<Bar> pf = Foo::hop;
TriFunction<Integer> pg = (x, y, z) -> x + y + z;
Bar bara = pf.apply(a, b, c);
For primitive types better define own interfaces without generic parameter types. Above pg needs 3 times to unbox the wrapper objects, and one time to box it again to an object.
The package java.util.function contains many functional interfaces, like BinaryOperator and IntBinaryOperator.
In Java 8, you can use method references. More information here: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
Basically, Java 8 gives interfaces with only one method the special property that they can be used (sort of) like function pointers. You can assign a lambda or a method reference to an object of such a type.
For example, somewhat related to your question:
public class HelloWorld {
public interface Function <T> {
T op(T x, T y);
}
public static class Functions {
static int add(int x, int y) { return x + y; }
static int sub(int x, int y) { return x - y; }
}
static Function<Integer> f1, f2; // <-- "function pointer"
public static void main(String []args) {
f1 = Functions::add; // <-- static method reference
f2 = Functions::sub; // <-- static method reference
System.out.println("Test: " + f1.op(1,2) + ", " + f2.op(1,2));
}
}
This code prints, as you'd expect:
Test: 3, -1
So that part of your question should work. However, the part where you define a generic addition is more problematic, because Java doesn't allow you to overload the operator '+'. So the following will not compile in Java:
T add(T x, T y) {
return x + y; // compile error -> no '+' defined for T
}
If you need T to be base types, you'll need to define your f1 and f2 for each base type you want to use. See also this question: Can I do arithmetic operations on the Number baseclass?
I am not sure if I get your question correctly, but have a look at this stackoverflow post.
There are several answers on how to implement function pointer in java.
EDIT
I am not experienced enough in C++ to provide a code sample.
EDIT 2
According to the post I mentioned above, you could try something like this:
public class WithFunction {
//Empty constructor, can be left out
public WithFunction () {...}
//The function you want to reference
public int myReferencedFunction () {...}
}
Then
public class MethodCaller {
public static Object call (Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
//catch Exceptions
}
}
Then you can have it like
public static void main (String [] args) {
WithFunction obj1 = new WithFunction();
Object result = MethodCaller.call (obj1, "toString");
int result = (int) MethodCaller.call (obj1, "myReferencedFunction");
}
Notice:
You need to catch a lot of exceptions. Strong error handling needed..
If you use an interface, you can also implement it multiple times and should have the freedom you need
Consider this:
public class Test {
public static int numberOfInstances = 0;
public int myInstanceID;
public String myInstanceName;
The static variable doesn't need to be called within an instance, it's available everywhere like this:
Test.numberOfInstances
When creating an instance, I only do this into my constructor:
public Test(int id, String name) {
myInstanceID = id;
myInstanceName = name;
numberOfInstances += 1;
}
I've recently discovered the this keyword and have noted some of its uses:
public Test() {
this(numberOfInstances + 1, "newInstance");
numberOfInstances += 1;
}
From what I've noticed, the this keyword allows you to call another one of the class' constructors. It also allows you to do this:
public Test(int x, int y) {
this.x = x;
this.y = y;
}
With java, I highly disagree with this style; same variable names, and I don't see the point of using this, especially after looking at the docs example. I look at this:
public Test(int a, int b) {
x = a;
y = b;
However, the use of the this keyword isn't necessary; In my code, I have a variables in my class (e.g. xCoordinate) where I don't use the this keyword (it's not static).
What I've been struggling to understand is what the difference is between non-static variables and this variables. Is there a difference? In one of my classes (the Paddle for Pong), I have this:
public class Pong {
public int xCoordinate;
public int yCoordinate;
and so on...
I never use the this keyword anywhere, and the data is stored within it's own instance.
Bottom line, my question is what is the difference between non-static variables and this.variables. Is it a standard coding practice? Why would I ever you the this keyword on non-static variables?
I think you may have almost answered your own question. You provided the function
public Test(int x, int y) {
this.x = x;
this.y = y;
}
However, what do you think would happen if you wrote it this way instead?
public Test(int x, int y) {
x = x;
y = y;
}
Noticed that I removed the this in the second function. Therefore, x and y would just be referring to the local x and y variables. this allows you to specify that you actually want to use the non-static class variables x and y.
If, as is typical, the parameter variable names of a constructor (say x) are the same as fields of the class, then the field names are shadowed by the parameters passed.
this is used in this case to disambiguate: this.x denotes the field x. It makes perfect sense. this means "reference to the current instance".
So, statements like this.x = x; are quite common.
If you still continue to dislike the Java style, and you adopt m_x-style notation for class fields, then you can write m_x = x; in your constructor. As you rightly point out, this is then not required.
this is also used as the notation for delegating constructors, as you point out.
The "this" keyword allows you to difference between method and instance variables:
public class Point {
private int x;
private int y;
public void add(int x, int y) {
this.x += x;
this.y += y;
}
}
There is no this variables. It's just used to tell the compiler that the variable you want to change is the declared field and not the local variable, in case they have the same name.
For the constructor part, this is just a shortcut for classes which have multiple constructors. You can write the code once and just call that from the alternative constructors.
There is also a similiarly used keyword super, which allows you to call methods and constructors of the superclass:
public SomeClass(int x) {
super(x);
super.someMethod(); // even if we would have overridden someMethod(),
// this will call the one from the superclass
}
Here's one instance where you would need the 'this' keyword:
public class Pong {
public int xCoordinate;
public int yCoordinate;
public Pong (int xCoordinate, int yCoordinate) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
}
}
I'm having trouble accessing a variable of a class I have created within a for loop.
The class I have created is fairly simple and just combines a vector and a double value.
public class VectorDistance
{
Vector2d v;
double d;
public VectorDistance(Vector2d v, double d)
{
this.v = v;
this.d = d;
}
}
and within a method in another class which inherits an ArrayList of these vector distances, I'm trying to access the variables of it but it doesn't seem to want to access it. But for whatever reason it won't let me access it. I've tried value.get(0) etc but that does not work. Any help would be greatly appreciated. It is declared as an ArrayList with type VectorDistance throughout the code.
public String NewPositionCheck(Vector2d checkPosition, int blockSize, Types.ACTIONS fromPrevious, List<Types.ACTIONS> previousPositions, ArrayList<Observation>[][] grid, int i, ArrayList <VectorDistance> vd)
{
double closest = Double.MAX_VALUE;
for (VectorDistance value : vd)
{
}
}
all i want is to find the smallest value in the ArrayList, by comparing its double value (d) with value "closest" and then store that position as an integer (which i forgot to add)
You have to declare them public, to access them outside of its class
public Vector2d v;
public double d;
Or much better solution is to create getters/setters (just google it)
Also - modern IDE like netbeans, eclipse etc. even have option to create getters/setters for you)
You have to specify access modifier as public as below:
public class VectorDistance
{
public Vector2d v;
public double d;
public VectorDistance(Vector2d v, double d)
{
this.v = v;
this.d = d;
}
}
More professional way would be declaring access methods, with the name getSomething() or setSomething(ValueType val)
How to call distanceTo(Point p) of Point.java into Point2.java under a method takes no parameter? There should be a way but I cannot find from my materials. Could anybody help me? It has been doing 2 days. Please help...
---------------------Point.java---------------------------------
public class Point{
private int x;
private int y;
//x and y coordinates as parameters
public Point(int x, int y){
this.x = x;
this.y = y;
}
//I want to call this method by calling a method which taken no parameter in Point2.java.
public double distanceTo(Point p){
return Math.sqrt(((x - p.x) * (x - p.x)) + ((y - p.y) * (y - p.y)));
}
}
---------------------ClonePoint.java---------------------------------
public class ClonePoint{
private int a;
private int b;
//x and y coordinates as parameters
public ClonePoint(int a, int b){
this.a = a;
this.b = b;
}
//I failed with this way. Can anybody correct me?
public double measureDistance(){//it should be takes no parameter.
return distanceTo(ClonePoint p)
}
}
----------------------PointDriver.java-----------------------------
public class PointDriver {
public static void main(String [] args) {
Point2 nn = new Point2(11, 22);
Point2 mm = new Point2(33, 44);
System.out.println(nn.distanceTo(mm)); //I succeeded with this!
System.out.println(nn.measureDistance(mm)); //But I got an error illegal start of expression
}
}
#Evan a class is a generalized container for your things. A car, a person, a point (in your case).
Everytime you want to "create" one or more object of your defined class, you instantiate them:
Person evan = new Person();
Person rob = new Person();
both of us are person, you don't really need to define class Person1 and Person2!
And in a class you should define the methods used to "relate" to other similar objects.
For example:
// In Person.java
public void greet(Person p) {
System.out.println("My name is "+this.name+". Nice to meet you +"p.getName());
}
// In main
rob.greet(evan); // it now gives compile errors of course but take the point :P
What you want to achieve is to create a better and more complete Point class with all the methods you want to use. In the end, just initialize more Point objects (same class!) in your main and play with them.
Hope it helps :)
EDIT
Ok, perhaps I've got what your homework wants you to perform.
A "parameter-less" method measureDistance() should make you wonder one important thing: "distance FROM which point????".
Obviously, if the function takes no parameters all the information needed to that calculus must be in the object which calls it. Don't you think?
So, you probably want to achieve a secondary class (if you really need to define it as Point2 it's ok, but change that name because it's confusing) which can take a Point in its constructor (saving this information in itself) and then use that Point to measure distance from it.
Example
public class Point2{
private int a;
private int b;
private Point startingPoint;
public Point2(int a, int b, Point p){
this.a = a;
this.b = b;
startingPoint = p;
}
// Computes the distance from starting point to this
public double measureDistance(){//it takes no parameter.
return startingPoint.distanceTo(a, b);
}
/*
if you can't edit distanceTo() it gets a little verbose but you must create a
Point with Point2 coordinates - remember this example when you will study Inheritance
public double measureDistance() {
Point endingPoint = new Point(a, b);
return startingPoint.distanceTo(endingPoint);
}
*/
}
First, it is not good idea to duplicate a class that does the same thing because you are doing extra unneeded work. Second, if you make various point types, you are loosing the advantage of seamless compatibility between them.
Then, if you want to call method from other class you can do it like this:
NameOfOtherClass.SomeMethod()
But you have to declare the SomeMethod in the other class as static...
public static double SomeMethod() { ... };
But then you can't use the method to access the data of your concrete points you have created in your code, so any data should be put into parameters.
If you want to do it your way, you have to just add a parameter to public double measureDistance()
function so the function has access to another point to measure distance to.
I'm kind of new to Java. I want a method that will use submethods(?). I want something like this:
Math.Addition(1, 1, X in this case, integer of users choice for the output);
The output would be stored in the variable X. But I also want to do something like this:
Math.Subtraction(2, 1, X);
How would I do this?
Create a class called Math.
and Have two methods inside it named 'Addition' and 'Subtraction' with required arguments and put the logic for each inside the method.
public class Math {
public static int X;
public static int Addition(int a, int b, String choice) {
X = a+b;
return X;
}
public static int Substraction(int a, int b, String choice) {
X = a-b;
return X;
}
}
You'll probably need to return the value in order to assign to x. e.g.
X = myClass.add(1,1);