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
Related
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 5 years ago.
As per my understanding, in the OOP paradigm, the class is the blueprint of the objects that are created as per need. In context to the definition below from the Java docs which exactly is the current object that the this keyword is a reference to in the following snippet? The constructor that is being called is of the Point class. I also read this post which says that classes are not objects. What am I missing 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;
}}
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
"This" usually tells you that,when you are using any variable that starts with "this" meaning you are using variable that belongs to this class. Not to any method or something.
In your case you have x as parameter and x as class variable . Both are having same name. When you say this.x , it refers you are calling class variable. and When you say x, it means you are using parameter of course inside that method. Same applicable for y also
One use,basically just to avoid confusion.
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;
}
}
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.
public class NotActuallyImmutable {
private final int x;
public NotActuallyImmutable(int x) {
this.x = x;// line 1
}
public int getX() {
return x;
}
}
public class Mutable extends NotActuallyImmutable {
private int x = 123;
public Mutable(int x) {
super(x);
}
public int getX() {
return x++;
}
}
now in my main class
NotActuallyImmutable n = new Mutable(42); // line2
int x = n.getX();
System.out.println("x is"+x);
I am expecting the output as 42 but it return the output as 123. I am expecting 42 because at line 2 I am making object of class Mutable and then at line 1 I am setting value as 42. so when i do n.getX() I should get the this latest value not the default 123. I know Ii am missing something but not able to figure out the logic behind it?
The problem is that the field x in Mutable and the field x in class NotActuallyImmutable are not the same. The x that is returned by getX() is the one in Mutable (because the getX() that is invoked is Mutable.getX(), not NotActuallyImmutable.getX()).
Note that if you removed the instance field from Mutable, then you would have a compiler error because NotActuallyImmutable.x is private to NotActuallyImmutable and not accessible to any code in Mutable.
If you made NotActuallyImmutable.x a protected field, then Mutable.x would shadow it and you would still have the same behavior. If you removed Mutable.x in this case, you would still have a compiler error because you were trying to increment a final field.
If you remove Mutable.getX(), then the x that would be returned by getX() would be NotActuallyImmutable.x, despite there being another field of the same name in Mutable.
The private int x in Mutable and the private int x in NotActuallyImmutable are completely different fields that just have the same name.
This isn't a problem for the compiler because you can't access a private field from another class. So as far as the compiler is concerned, when you define Mutable, the x in NotActuallyImmutable is invisible and might as well not exist.
It is of course confusing for the programmer. If you rename one of the fields to y (and the getter method to getY) the behaviour seems much more intuitive.
NotActuallyImmutable n = new Mutable(42); // line2
This means you have an object of type NotActuallyImmutable but the instance of created object is Mutable.
so in this code your dealing with Mutable object which will return 123. as the number you passed is saved in NotActuallyImmutable not in Mutable,
n has two different x values which are visible in different contexts, the parent class's private member variable and the child class's private member variable.
NotActuallyImmutable n = new Mutable(42); // line2
Creates a new Mutable. Executes parent(x) which sets the parent class's x to 42.
int x = n.getX();
n is a Mutable instance so this calls Mutable's getX() which returns Mutable's value for x (123) rather than the parent's.
I agree with Nice explanations given in above answers. But to to just brief the final understanding. As i am doing new Mutable(42).getX(), jvm first will look in Mutable object to get the value of X not inside NotActuallyImmutable. If i remove getX() method from Mutable , i get the expected(as per my expectation) value i.e 42.
This example gets messy becoz variable name i.e X is same in parent and child class but good for understanding concept
Though I'm trying to understand why "this" is needed, I'm very confused about its purpose. For instance, I coded the following:
public static void main (String args[])
{
SandboxClass1 temp = new SandboxClass1(1,2,3);
System.out.println(temp.getX());
System.out.println(temp.getY());
System.out.println(temp.getZ());
System.out.println("----------------------------");
SandboxClass1 temp2 = new SandboxClass1(4,5,6);
System.out.println(temp2.getX());
System.out.println(temp2.getY());
System.out.println(temp2.getZ());
}
public class SandboxClass1
{
private int x = 1;
private int y = 1;
private int z = 0;
public SandboxClass1(int x, int y, int zz)
{
this.x = x;
this.y = y;
z = zz;
}
public int getX()
{
return(this.x);
}
public int getY()
{
return(this.y);
}
public int getZ()
{
return(this.z);
}
}
Why do I need to code "this.z = zz"
when I could just as well write, "z = zz"?
You don't, in this case. It's only required when you must eliminate ambiguity, like when parameters and instance variables share a name.
Some people prefer to use "this" to remove conceptual ambiguity and explicitly state that the code references an instance variable.
(On a side note, the parentheses around the return values are unnecessary and a bit noisy, IMO.)
In your SandboxClass1 constructor, you have two pairs of variables each called x and y. There's the x and y declared on the object itself ("private int x = 1"), and the separate x and y that are parameters to the constructor ("int x").
The local (parameter) variable shadows the class variable. So if in the constructor you just did
x = x;
the assignment would have no effect.
The keyword this is a reference to the object that the method/constructor was called on. In the statement
this.x = x;
you're using it to assign to the other x at class level. By qualifying the name, you can tell them apart.
It's not necessary to use this with the z/zz assignment because they have different names.
It's also not necessary in the getX/Y/Z methods because there are no local variables in those methods shadowing the relevant class variables. It does no harm though.
In the SandboxClass1 constructor two of the parameters (x and y) hide class variables because they are the same name. If you want to assign the class variable x to any value while in the code>SandboxClass1 constructor, you must address it using this.x to tell the compiler that "I want to assign the class scope variable named x, and not the method scope variable named x". The same applies to y.
Since the parameter z does not hide the class scope variable named zz you do not need to tell the compiler the scope of the zz variable, the class scope zz is the only recognized variable so that is the one that gets assigned.
It has the same effect. this is needed if there is a local variable which overrides a field of the class; then you get the local variable and not the class field.
An additional advantage you can indicate the variables better. If there is a this; it's a field; local variable otherwise.
the keyword this is used to refer to an attribute that is in the class. The keyword this was created to distinguish between class attributes and method parameters. like this:
public class human
{
public void setName(String name)
{
// the first name is a reference to the class attribute name
this.name = name;
// the second name is a reference to the method parameter name
}
// definition of the class attribute name
private String name;
}
when you use the keyword this it refers to the name variable inside the class heres an example where you don't need to use this:
public class Human
{
public void setName(String myName)
{
name = myName
}
private String name;
}
see now there is only 1 variable named name and there is only one variable named myName. In the other example there was 2 variables named name. One was a class attribute and one was a method parameter.
'this' operator just refines that property/field belongs to class you're working in. It's useful whe you have, for example, two variables with the same name:
this.zz = zz;
Unlike, say, Objective-C, "this" is optional when the method or variable is local, and there is no other conflicting use of the same name.
It comes in handy in conflicting-name cases, though, such as in methods that set instance variables such as void setOnionCount(int onionCount) where you would like to use "onionCount" for the formal parameter but still have "onionCount" as the instance variable name. In such a case you can do this.onionCount = onionCount; and everyone is happy (except, I suppose, those in the Peanut Gallery who'll object to this technique).
"this" is also absolutely necessary in cases where you need to pass a reference to the current object to some other class, of course.
hey this is use to provide reference of invoking object. That i.e say suppose ur class is box then if you want to provide it's object then you can provide it within the class box using this keyword.
class Box {
int x;
public Box(int x){
this.x = x;
}
}
here in this case if your object is ob (i.e Box ob = new Box(1)) then the reference it will be passed to the itself.
Note: you cannot use this keyword outside of the class. If you use so then it will give reference of another class.
for complete detail on this keyword refer following link
http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html