Professional Documents
Culture Documents
(/) About (/about)
C# (http://www.learncs.org) Jobs (/recruitcodersjobs)
(/cn/) (/en/)
Welcome (/en/Welcome) / Objects
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.
Let start with an example:
class Point {
int x;
int y;
}
Execute Code
This class defined a point with x and y values.
In order to create an instance of this class, we need to use the keyword new .
Point p = new Point();
Execute Code
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.
We can define our own constructor:
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
Code Window Run Reset Solution
this.y = y;
}
Output Window Expected Output Show Code Window
}
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Execute Code
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)
This means we can not longer use the default constructor new Point() . We can now only use the defined
constructor new Point(4, 1) .
class Point {
int x;
int y;
Point() {
this(0, 0);
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Execute Code
p.x = 3;
p.y = 6;
Execute Code
Methods
We can now define methods on Point .
class Point {
... // Our code previously
void printPoint() {
System.out.println("(" + x + "," + y + ")");
}
Point center(Point other) {
// Returns the center between this point the other point
// Notice we are using integer, we wan't get an accurate value
return new Point((x + other.x) / 2, (y + other.y) / 2);
}
Code Window Run Reset Solution
}
(http://www.dmca.com/Protection/Status.aspx?ID=fd56e7e29e1f43ccbe7ce1023cb5781c)
Copyright © LearnJavaOnline.org. Read our Terms of Use (/tos) and Privacy Policy (/privacy)
Public and Private
Although we'll talk about modifiers later on, it's important to understand the different between private and public
variables and methods.
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)