|
|
|
|
|
|
|
|
|
|
||||||||||
|
Java
is composed of classes. A class is a set of objects and methods which are
related. Each class has fields, which can be thought as variables in conventional
programming languages. Fields say what an object is. And methods say what
an object can do. When we define a class, we define its fields as well
as its methods. We can define a 2D point as:
class TwoDPoint {
However, this is not more than a data structure. For example, we want this object to response the message: How far is it from the origin ? Thus, we can extend this class by adding: class TwoDPoint {
double
length() {
} Whenever we call the following; TwoDPoint
p = new TwoDPoint();
Please note that we used a special word: "this" In order to access the fields of an object, we use "this" keyword. It can be assumed as a copy of the calling object, which is "p" in our sample code segment. We created an object by using an empty constructor; which is not explicitly defined in the class definition. Instead, we can define a new constructor for TwoDPoint class: TwoDPoint(double
xv, double yv) {
So, we can create a new object (which is called instance of a class, officially) as: TwoDPoint
p2 = new TwoDPoint(3, 4);
This code segment produces the same result as the first one.
|
|
|
|
|
|
|