Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
95
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 3 Java Class Design

Polymorphism

The Greek roots of the term polymorphism refer to the “several forms” of an entity. In the real world, every message you communicate has a context. Depending on the context, the meaning of the message may change and so may the response to the message. Similarly in OOP, a message can be interpreted in multiple ways (polymorphism), depending on the object.

For example, in function overloading (one of the polymorphic constructs in Java), you can provide methods with the same name but with different numbers of arguments or types of arguments. The concept is simple, yet it provides a lot of power and flexibility to the programmer. In FunPaint, you can fill the shapes with different colors. Methods like fillColor() can either take the color argument as RGB (Red, Green, Blue) values or as HSB (Hue, Saturation, Brightness) values. The call for the same method, fillColor(), behaves differently based on the provided arguments; this is an example of compile-time polymorphism.

Let’s assume that you have a method named area() in the Shape base class. The area() method returns the area of the drawn shape. Hence, area() is implemented (overridden) in all the derived classes of Shape. A Shape reference can point to any derived class object. When you call the area() method from the Shape reference, it results in calling the area() method of the actual object type (i.e. the dynamic type of the object). This dynamic behavior is known as runtime polymorphism.

We packed a lot of concepts and terminology into one simple example. Don’t worry if you don’t quite digest them all at once. You’ll be learning more about them throughout this book.

Class Fundamentals

A class is a fundamental abstraction entity and building block in OOP. A class encapsulates state (data) and behavior (operations) of an entity. For example, a Circle class defines a blueprint for individual circle objects. This Circle class might have state information such as radius and operations such as area() and fillColor(). The Circle class

encapsulates state and operations of the circle in a single entity and provides a new abstraction. From an object-oriented programming point of view, it is important to understand that a class defines a new type that could be used by other classes in a program.

Let’s look at an example of a class and analyze its various parts (Figure 3-2). This example declares the class Circle, which has the member-variables x, y, and radius of type Integer and the two member-methods, area() and fillColor().

Figure 3-2.  A sample class Circle and its various parts

A class is a template (or blueprint), and an object is an instance of a class.

48

Chapter 3 Java Class Design

Object Creation

You create classes to use them in your programs. You can create an instance (an object using the services of a class). At a high level, there are three steps to using an object in a program.

Declaration: You need to provide a variable declaration that consists of the type-name (the class you want to use) and the object-name. For example, following statement declares a variable circleObj of type Circle:

Circle circleObj;

Instantiation: You use the keyword new to create an instance; the keyword allocates required memory for the object. In this example, you instantiate the circle object by using the following statement:

Circle circleObj = new Circle ();

Initialization: A special method, which you call as a constructor, is invoked automatically. The constructor initializes the newly created object.

Constructors

Each time you create an object, a constructor of that class gets called. You can make use of the constructor to initialize the newly created object by setting the initial state of the object, and you can acquire some resources (such as file handles). The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Every class has a constructor. If you do not explicitly write a constructor for a class, the Java compiler provides a default constructor (without any parameter) for that class.

Assume that you are implementing the Circle class in the FunPaint application. A Circle should remember its center and its radius, so you have three fields: xPos, yPos, and radius.

class Circle {

int xPos, yPos, radius;

}

What happens when you create a new Circle object? The values of xPos, yPos, and radius will be initialized to the value 0 by default since they are of type Integer. However, this is not desirable for creating proper Circle objects. Let’s define default values for the variables xPos, yPos, and radius, in a default constructor:

public Circle() {

xPos = 20; // assume some default values for xPos and yPos yPos = 20;

radius = 10; // default radius

}

49

Chapter 3 Java Class Design

As you can see here, a constructor has the same name as the class and doesn’t have any return type. A default constructor does not have any arguments. A default constructor gets invoked when you create a new object without passing any arguments.

Let’s check whether this default constructor gets invoked or not when you try to instantiate an object of Circle. For that you’ll implement toString() method for printing the values of the Circle members (Listing 3-1). (Note: You don’t have to call toString() method explicitly as in this code—it will get called automatically. You’ll learn more about it in the “Runtime Polymorphism” section of this chapter).

Listing 3-1.  Circle.java

//A 2D Circle class with xPos and yPos fields to store the coordinates for center point

//and radius field to store the radius value of the circle

class Circle {

private int xPos, yPos, radius;

//default constructor initializing all the three fields public Circle() {

xPos = 20; // assume some default values for xPos and yPos yPos = 20;

radius = 10; // default radius

}

//overridden toString method to print info on Circle object in string form public String toString() {

return "center = (" + xPos + "," + yPos + ") and radius = " + radius;

}

public static void main(String[]s) {

//Passing a object to println automatically invokes the toString method

System.out.println(new Circle());

}

}

It prints

center = (20,20) and radius = 10

Yes, your default constructor is working. Got it? Now, can you see what’s wrong with this constructor?

public void Circle() {

xPos = 20; // assume some default values for xPos and yPos yPos = 20;

radius = 10; // default radius

}

A constructor does not have a return type, and here you’ve given a void return type. This is not a constructor, but it is a method named Circle in this class! Beware: Java allows you to declare methods with same name as the class name, but it is not a good practice to make use of this feature (since it will confuse the programmers reading your code).

A constructor does not have a return type. If you define a return type, it is not a constructor, but a method! Beware and avoid making this common mistake.

50

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]