I am new to java and I always was taught it was always class.method and now this code which has another.getX is confusing me greatly. I never realized parameter or argument.method was possible Can someone explain how it works?
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point() {
this(0,0);
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double distance (){
double distance = Math.sqrt((x - 0) * (x - 0) + (y - 0) * (y - 0));
return distance;
}
public double distance (int x, int y){
double distance = Math.sqrt((x-this.x) * (x-this.x) + (y-this.y) * (y - this.y));
return distance;
}
public double distance (Point another){
double distance = Math.sqrt((another.x - x) * (another.x - x) + (another.y - y) * (another.y - y));
return distance;
}
}
It is possible.
As always for this kind of things, it is defined very well in the Java Language Specification, § 15.1. This is an excerpt:
If an expression denotes a variable, and a value is required for use in further evaluation, then the value of that variable is used. In this context, if the expression denotes a variable or a value, we may speak simply of the value of the expression.
That means that someObject.someMethod()
may produce a value with a result type.
Here's an example:
class A {
B getB() {
return new B();
}
}
class B {
C getC() {
return new C();
}
}
class C {
String getString() {
return "Hello World!";
}
}
You can "chain" your method calls like this:
A myA = new A();
String str = myA.getB().getC().getString().toUpperCase();
System.out.println(str); // Prints "HELLO WORLD!"
What happens is this:
myA
is an A
. A.getB()
returns a B
. B.getC()
returns a C
. C.getString()
returns a String
. returns a
String , thus the final result is a
String , which is stored into the
str` variable. A few more notes: SomeClass.someMethod()
denotes a static method . The class name may be omitted if the current class is SomeClass
. someVariable.someMethod()
, however, is an instance method , it can only be called on an instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.