Professional Documents
Culture Documents
Objects: Class Point (Int X Int y ) Execute Code
Objects: Class Point (Int X Int y ) Execute Code
Objects
Everything in Java is within classes and objects. Java objects hold a state, state are variables which are saved
together within an object, we call them fields or member variables.
class Point {
int x;
int y;
}
Execute Code
Execute Code
new .
In this case, we used a default constructor (constructor that doesn't get arguments) to create a Point. All classes
that don't explicitly define a constructor has a default constructor that does nothing.
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
Code Window
this.y = y;
}
Output Window
}
Execute Code
This means we can not longer use the default constructor new Point() . We can now only use the defined
constructor new Point(4, 1).
Run Reset Solution
We can define more than one constructor, so
Point can be created in several ways. Let's define the default
constructor again. Expected Output Show Code Window
Execute Code
Point center(Point other) {
Notice the //
usage of the
Returns thekeyword
this here. Wethis
center between can use
pointit within a constructor
the other point to call a different constructor (in
// Notice
order to avoid we are using
code duplication). integer,
It can only bewethewan't get within
first line an accurate value
the constructor.
return new Point((x + other.x) / 2, (y + other.y) / 2);
We also
}
used thethis keyword as a reference of the current object we are running on.
Code Window
} we defined
After p we can accessx and y .
Output Window
Execute
p.x = 3;Code
Public
p.y = 6;
and Private
Although we'll talk about modifiers later on, it's important to understand the different between private and public
Execute Code
variables and methods.
When using the keyword private before a variable or a method, it means only the class itself can access the
variable or method, when we're using public it means everybody can access it. We usually see constructors
defined as public, variables defined as private and methods are separated, some public and some private.
Exercise
Write a new method in Point called scale , that will make the point closer by half to (0,0). So for example, point (8,
4) after scale will be (4, 2).
Start Exercise
(http://www.spoj.com/?utm_campaign=permanent&utm_medium=banner&utm_source=learnx)
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)
Code Window
Output Window
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)