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

Chapter 3 Java Class Design

Points to Remember

Here are some interesting rules regarding method overloading that will help you when taking the OCPJP exam:

Overload resolution takes place entirely at compile time. In the next section, you’ll learn about runtime polymorphism where the method call is resolved at runtime.

You cannot overload methods with the methods differing in return types alone.

You cannot overload methods with the methods differing in exception specifications alone.

For overload resolution to succeed, you need to define methods such that the compiler finds one exact match. If the compiler finds no matches for your call or if the matching is ambiguous, the overload resolution fails and the compiler issues an error.

The signature of a method is made up of the method name, number of arguments, and types of arguments. You can overload methods with same name but with different signatures. Since return type and exception specification are not part of the signature, you cannot overload methods based on return type or exception specification alone.

Inheritance

An important feature supported by object-oriented programming is the hierarchical classification of knowledge using inheritance. Hierarchical models are easy to understand. For example, you can logically categorize vehicles as two-wheelers, three-wheelers, four-wheelers, etc. In the four-wheelers category, there are cars, vans, buses, trucks,

etc. In the cars category, there are hatch-backs, sedans, SUVs, etc. When you categorize hierarchically, it becomes easy to understand, model, and write programs. In OOP, you can create such hierarchies easily using inheritance.

Consider a simple example used in earlier sections: class Shape is a base class while Circle and Square are derived classes. In other words, a Circle is a Shape; similarly, a Square is a Shape. Therefore, an inheritance relationship can be referred to as an is-a relationship.

In the Java library, you can see extensive use of inheritance. Figure 3-3 shows a partial inheritance hierarchy from java.lang library. The Number class abstracts various numerical (reference) types such as Byte, Integer, Float,

Double, Short, and BigDecimal.

Object

Number

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Byte

 

Integer

 

Float

 

Double

 

 

 

 

 

 

 

 

 

 

 

Figure 3-3.  A partial inheritance hierarchy in java.lang package

63

Chapter 3 Java Class Design

The class Number has many common methods that are inherited by the derived classes. The derived classes do not have to implement the common methods implemented by the Number class. Also, you can supply a derived type where the base type is expected. For instance, a Byte is a Number, which means you can provide an object of

Byte where an object of Number is expected. You can write general purpose methods (or algorithms) when you write methods for the base type. Listing 3-12 shows a simple example.

Listing 3-12.  TestNumber.java

public class TestNumber {

// take an array of numbers and sum them up public static double sum(Number []nums) {

double sum = 0.0; for(Number num : nums) {

sum += num.doubleValue();

}

return sum;

}

public static void main(String []s) {

//Create a Number array Number []nums = new Number[4];

//assign derived class objects nums[0] = new Byte((byte)10); nums[1] = new Integer(10); nums[2] = new Float(10.0f); nums[3] = new Double(10.0f);

//pass the Number array to sum and print the result System.out.println("The sum of numbers is: " + sum(nums));

}

}

This program prints

The sum of numbers is: 40.0

In the main() method, you declare nums as a Number[]. A Number reference can hold any of its derived type objects. You are creating objects of type Byte, Integer, Float, and Double with initial value 10; the nums array holds these elements. (Note that you needed an explicit cast in new Byte( (byte) 10) instead of plain Byte(10) because Byte takes a byte argument and 10 is an int.)

The sum method takes a Number[] and returns the sum of the Number elements. The double type can hold the largest range of values, so you use double as the return type of the sum method. Number has a doubleValue method and this method returns the value held by the Number as a double value. The for loop traverses the array, adds the double values, and then returns the sum once you’re done.

As you can see, the sum() method is a general method that can handle any Number[]. A similar example can be

given from the Java standard library where java.lang.Arrays class has a static method binarySearch():

static int binarySearch(Object[] a, Object key, Comparator c)

This method searches a given key (an Object type) in the given array of Objects. Comparator is an interface declaring the equals and compare methods. You can use binarySearch for objects of any class type that implements this Comparator interface. As you can see, inheritance is a powerful and useful feature for writing general-purpose methods.

In the FunPaint example, there is an inheritance relationship between base type Shape and its derived types such as Circle and Square. What is the advantage of associating these classes by inheritance?

64

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