Building a "Wrapper" class in Java - java

I'm wondering if anyone knows a way to wrap an object inside another one in Java. So if we start with a class A, I essentially need to build a subclass (class B) that takes an instance of class A in the constructor and initialises all it's fields to be the same as those of class A. The idea is that B becomes A, but just adds some extra stuff to it. I'm wondering if there's any way to do this without having to manually assign all the fields (also it's impossible to assign final fields this way so that's another thing to consider).
This is my first question ever so I apologise if it's not clear. Please feel free to request clarification if required.
Thanks for any help,
Andrei

You cannot change final variables, and you'll have to change the other fields manually. You should really just create another object entirely.
public class A {
private final int x;
private int y;
public A( int x, int y ) {
this.x = x;
this.y = y;
}
...
}
public class B extends A {
public B( final A a ) {
super( a.getX(), a.getY() );
}
...
}

Related

Is overriding static field with static block bad practice?

I want to create data structures to capture the following ideas:
In a game, I want to have a generic Skill class that captures general information like skill id, cool down time, mana cost, etc.
Then I want to have specific skills that define actual interaction and behaviours. So these would all extend from base class Skill.
Finally, each player will have instances of these specific skills, so I can check each player's skill status, whether a player used it recently, etc.
So I have an abstract superclass Skill that defines some static variables, which all skills have in common, and then for each individual skill that extends Skill, I use a static block to reassign the static variables. So I have the following pattern:
class A {
static int x = 0;
}
class B extends A {
static {
x = 1;
}
}
...
// in a method
A b = new B();
System.out.println(b.x);
The above prints 1, which is exactly the behaviour I want. My only problem is that the system complains about I'm accessing static variable in a non-static way. But of course I can't access it in that way, because I only want to treat the skill as Skill without knowing exactly which subclass it is. So I have to suppress the warning every time I do this, which leads me to think whether there is a better/neater design pattern here.
I have thought about making the variables in question non-static, but because they should be static across all instances of the specific skill, I feel like it should be a static variable...
You should generally avoid such use of global state. If you know for sure that the field x will be shared across all instances of all subtypes of the base class, then the correct place to put such a field is probably somewhere other than the base class. It may be in some other configuration object.
But even with your current configuration, it just does't make sense since any subclass that modifies the static variable will make the variable visible to all classes. If subclass B changes x to 1, then subclass C changes it to 2, the new value would be visible to B as well.
I think that the way you described in the question, every subclass should have its own separate static field. And in the abstract base class, you can define a method to be implemented by each subclass in order to access each field:
abstract class A {
public abstract int getX();
}
class B extends A {
public static int x = 1;
public int getX() {
return x;
}
}
class C extends A {
public static int x = 2;
public int getX() {
return x;
}
}
As already pointed out by some answers and comments, your approach won't work the way you want because every static block changes the static variable for all classes extending A.
Use an interface and instance methods instead:
public interface A {
int getX();
}
-
public class B implements A {
private static final int X = 1;
#Override
public int getX() {
return X;
}
}
-
A myInstance = new B();
System.out.println(myInstance.getX()); // prints "1"

"this" objects vs non-static objects

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;
}
}

Call a method from another class(not main class)

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.

Java constructor explanation please? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I dont understand how a constructor works
In the following code i know that we have a class, then two variables. When you create a variable you create a container for a value, so by declaring the variables x and y we created two containers, and they contain 0,0.
why the constructor, why the a and b?
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
Constructors are used to initialize instances of classes.
Each instance's x and y values are initialized to what you pass in to the constructor, here, the parameters are named "a" and "b".
In general, direct public access to instance variables is frowned upon, instead they'd be accessed through getters and setters.
This constructor is used in another class. In this case it looks like you're trying to make a "point on a graph" so with that assumption in another class you would use this constructor to make an instance of the Point class.
public class Example {
private Point pt;
public static void main(String[]args) {
pt = new Point(20,10);
}
}
This example creates a new instance of the Point class where x is 20 and y is 10.
We have the code here, I'll explain it line by line.
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
First of all we have the public class Point {, this is the start of the class. All of the classes functions/variables go inside of this brace.
public int x = 0;
public int y = 0;
x and y are being declared here. By declaring them outside of any of the funcions, we're making them global and accessible to the entire class. These two variables are public which means they can be accessed outside of the script, but because they are not static, they can only be called from outside of the script after a new instance of Point has been created.
public Point(int a, int b) {
This line of code is called the constructor. We can see this because it (a) doesn't have a return type and (b) shares the same name as the class. The instructor is called when a new instance of the class is created via the new keyword. I.E. new Point().
int a and int b are two required variables, so you must create your new instance of this class like so new Point(5, 10); where 5 represents A and 10 represents B.
Inside of your constructor you are setting the variables x and y to contain the two values passed to the constructor. So X will become 5 using my example, and Y will become 10.
X and Y will not be 0 because they have both already been created using the value of 0, and are now being set to a different value.
It is important to note that a constructor does not have to have parameters, and it could simply be written as public Point() { if you do not need to pass any parameters to it.
"Why the constructor? "
Answer: User "should" instantiate the class Point by giving 2 values to the variables. Which signifies whoever want to use Point, give value and use it.
"Why a and b?"
Answer: 2 explicitly given user values for the variables of Point class. You can even do like this forgetting a and b:
enter code here: public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Let me explain you by using a very easy understanding example so that you can be able to learn and adapt it with easily.
class store
{
protected String nameproduct;
protected String idproduct;
public store(String nameproduct, String idproduct) {
this.nameproduct = nameproduct;
this.idproduct = idproduct;
}
}
Based on what code above that we have declared nameproduct and idproduct as a String. Why I use protected because when you inheritance this class to other class that STILL RELATED so you don't need to declare those variables. So the variables are like a raw material that ready to build and the constructor is tool to developed it.
"x" and "y" values are initialized to what is passed from the constructor, in this case "a" and "b"
When the Point class is instantiated x and y has value 0. But when the class is instantiated by giving user values it make use of this constructor and make the value of x and y as user intended.
ie; one can create:
Point pt=new Point(); //point which has x and y as 0
OR
Point pt=new Point(10,5); //point which has x=10 and y=5

Java: Modifying variables without arguments

I'm just beginning to learn Java and I have been very frustrated about learning Java's scope rules. You see I wish to create a Method without the use of arguments/parameters.
In JavaScript, I can do this with ease using functions:
/** Function to increase 2 vars.
/** **/
function modifyNow(){
a++;
b++;
} // END
var a = 5;
var b = 10;
modifyNow();
// By this part, a and b would be 6 and 11, respectively.
Now this is saving me a lot time and simple since whenever the function is called, var a and b, already exist.
So, is there a way to do this in Java without having arguments like how I do it in JavaScript? Or is there another way around this?
Thank you, appreciate the help... ^^
What is the problem with having a and b as private variables in your class, and increment them in modifyNow()? And by the way everything in Java must be in a class. You can't have global code mangling around...
You can do this for class fields, not for local variables.
class Clazz {
int a = 5;
int b = 10;
public void modifyNow() {
a++;
b++;
}
}
// ...
Clazz c = new Clazz();
c.modifyNow();
Now, after each call to modifyNow, the fields are updated.
Global variables are bad. Without knowing your intent, I would say you need to add the variables as members to your class. They are accessible then from any member function.
You see I wish to create a Method without the use of
arguments/parameters.
The best answer is: don't!
If you nevertheless want this, look for public static variables.
class Foo {
int a = 5;
int b = 10;
public void modifyNow(){
a++;
b++;
}
}
You need to use what are called member variables, they are tied to an instance of your class.
public class MyClass
{
// these are Class variables, they are tied to the Class
// and shared by all instances of the class.
// They are referenced like MyClass.X
// By convention all static variables are all UPPER_CASE
private static int X;
private static int Y
// these are instance variables that are tied to
// instances of the class
private int a;
private int b;
/** this the default no arg constructor */
public MyClass() { this.a = 5; this.b = 10; }
/** this is a Constructor that lets you set the starting values
for each instance */
public MyClass(final int a, final int b) { this.a = a; this.b = b; }
public modifyNow() { this.a++; this.b++; }
/** this is an accessor to retrieve the value of a */
public int getA() { return this.a; }
public int getB() { return this.b; }
}
final MyClass myInstanceA = new MyClass();
myInstance.modifyNow();
// a = 6, b = 11
final MyClass myInstanceB = new MyClass(1, 2);
myInstance.modifyNow();
// a = 2, b = 3
Everytime you do a new MyClass() you will get a new independent instance of MyClass that is different from every other instance.
As you are learning JavaScript is not related to Java in anyway. It is a terrible travesty that they picked that name for marketing reasons.

Categories