22-04-2015 Intro to Java Chapter 11 笔记

来源:互联网 发布:广州凯媒通讯 知乎 编辑:程序博客网 时间:2024/05/16 09:30

Chapter 11 Inheritance and Polymorphism

1) Method Overloading:

1. 定义:

To override a method, the method must be defined in the subclass using the same signature
and the same return type as in its superclass.


2. super.super.toString() is syntax error.


3. 还有其他一些需要注意的。

3.1. An instance method can be overridden only if it is accessible. Thus a private method cannot
be overridden, because it is not accessible outside its own class. If a method defined
in a subclass is private in its superclass, the two methods are completely unrelated.


3.2. Like an instance method, a static method can be inherited. However, a static method
cannot be overridden. If a static method defined in the superclass is redefined in a
subclass, the method defined in the superclass is hidden. The hidden static methods
can be invoked using the syntax SuperClassName.staticMethodName.


2) Overloading and Overriding

1. 定义:

Overloading means to define multiple methods with the same name but different signatures.
Overriding means to provide a new implementation for a method in the subclass.


2. the difference between Overloading and Overriding

■ Overridden methods are in different classes related by inheritance; overloaded methods
can be either in the same class or different classes related by inheritance.
■ Overridden methods have the same signature and return type; overloaded methods
have the same name but a different parameter list.


Note:

Overloaded methods must have different parameter lists. You cannot overload methods
based on different modifiers or return types.


3. Exercise 11.11

3.1. 以前自己没有注意到:

  radius = radius; // Must use this.radius =radius

}


3.2. 注意不要忘了super

class B extends Circle

 

{

  Circle(radius);  // Must use super(radius)

  length = length; // Must use this.length =length

}

 

public double getArea()

{

 return getArea()*length; // super.getArea()

}


3) toString Method

Every class in Java is descended from the java.lang.Object class.

Note:
You can also pass an object to invoke System.out.println(object) or System.out.print(object). This is equivalent to invokingSystem.out.println(object.toString() or System.out.print(object.toString()). Thus, you could replace System.out.println(loan.toString()) withSystem.out.println(loan).


4) Polymorphism

定义:Polymorphism means that a variable of a supertype can refer to a subtype object.

Example:


What is Polymorphism?

An object of a subclass can be used wherever its superclass object is used. This is commonly known as polymorphism (from a Greek word meaning “many forms”). In simple terms, polymorphism means that a variable of a super-type can refer to a subtype object.


5) Dynamic Binding

Object o = new GeometricObject();
System.out.println(o.toString());


Object is the declared type.

GeometricObject is the actual type.

Which toString() method is invoked by o is determined by o's actual type. This is known as dynamic binding.


Matching vs Binding

Matching a method signature and binding a method implementation are two separate issues. The declared type of the reference variable decides which method to match at compile time. The compiler finds a matching method according to the parameter type, number of parameters, and order of the parameters at compile time. A method may be implemented in several classes along the inheritance chain. The JVM dynamically binds the implementation of the method at runtime, decided by the actual type of the variable.


6) Casting Objects and the instanceof Operator

1. The object casting is similar to the one used for casting among primitive data types.

Upcasting is done automatically.

Downcasting (explicit casting) has to used (SubclassName) casting notation.


Object o = new Circle();

Circle c = (Circle)o;

int age = 45;
byte newAge = (byte)age;


2. Casting a primitive type value is different from casting an object reference. Casting a primitive type value returns a new value. For example:

int age = 45;

byte newAge = (byte)age; // A new value is assigned to newAge

However, casting an object reference does not create a new object. For example:

Object o = new Circle();

Circle c = (Circle)o; // No new object is created

Now reference variables o and c point to the same object.


3. Why casting is necessary?

Consider the following code:

Object myObject = new Circle();

System.out.println("The circle diameter is " + ((Circle)myObject).getDiameter());


The variable myObject is declared as Object. The declared type decides which method to match at compile time. Using myObject.getDiameter() would cause a compile error, because the Object class does not have the getDiameter method. Thecompiler cannot find a match for myObject.getDiameter(). Therefore, it is necessary to cast myObject into the Circle type to tell the compiler that myObject is also an instance of Circle.


Casting is to ensure there is a method to match at compile time. It is controlled by declared type. It is about matching.

It is different from binding. Binding is decided by actual type. It is to decide which method to call, due to method overriding.


4. Exercise 11.27

The code below will not complied. It causes a runtime exception (ClassCastExcpetion).

public class Test {
public static void main(String[] args) {
Object fruit = new Fruit();
Object apple = (Apple)fruit;
}
}
class Apple extends Fruit {
}
class Fruit {
}

7) The Object’s equals Method

1. Like the toString() method, the equals(Object) method is another useful method defined in the Object class.

Example: 

Override the equals method in the Circle class to compare whether two circles are equal based on their radius as follows:
public boolean equals(Object o) {
if (o instanceof Circle)
return radius == ((Circle)o).radius;
else
return this == o;
}

2. equals() vs ==

The == comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. The equals method is intended to test whether two objects have the same contents, provided that the method is overridden in the defining class of the objects. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object.

3. equals(Object o)

When overriding the equals method, a common mistake is mistyping its signature in the subclass. For example, the equals method is incorrectly written as equals(Circle circle); instead, it should beequals(Object circle),

4. Exercise 11.29

What will be the outcome?

public class Test {
public static void main(String[] args) {
Object circle1 = new Circle();
Object circle2 = new Circle();
System.out.println(circle1.equals(circle2));
}
}

class Circle {
double radius;
public boolean equals(Circle circle) {
return this.radius == circle.radius;
}
}

The outcome is false. The Circle class has two overloaded methods:equals(Circle circle) defined in the Circle class and equals(Object circle) defined in the Object class, inherited by the Circle class. At compilation time, circle1.equals(circle2) is matched to equals(Object circle), because the declared type for circle1 and circle2 is Object. (Note that either the declared type forcircle1 and circle2 is Object would cause circle1.equals(circle2) to matchcircle1.equals(Object circle) by the compiler.)

因为declared type是object,所以equals(Object circle) is matched not equals(Circle circle),自己注意这点。Method signature 对照 object 的 declared type.

8) The ArrayList Class

1. ArrayList<AConcreteType> list = new ArrayList<AConcreteType>();
can be simplified by
ArrayList<AConcreteType> list = new ArrayList<>();
The concrete type is no longer required in the constructor thanks to a feature called type inference. The compiler is able to infer the type from the variable declaration. More discussions on generics including how to define custom generic classes and methods will be introduced in Chapter 19, Generics.

Example: ArrayList<String> cityList = new ArrayList<>();

2. The concreteType must be object type.

Not: ArrayList<int> list = new ArrayList<>();

Should be: ArrayList<Integer> list = new ArrayList<>();

3. Compare Array and ArrayList

add, insert and remove is very easy in Array.


4. Sorting in Array and ArrayList

Sort Array: java.util.Arrays.sort(array)

Sort ArrayList: java.util.Collections.sort(arraylist)

5. foreach loop

for (elementType element: arrayList) {
}

for (int number: list){
System.out.print(number + “ “);

}

9) Visibility


10) Preventing Extending and Overriding

Neither a final class nor a final method can be extended. A final data field is a constant.

Final class: can not be extended

Final method: cannot be overridden by its subclasses

0 0
原创粉丝点击