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

Chapter 15 OCPJP 7 Quick Refresher

Inheritance is also called an is-a relationship.

In overriding, the name of the method, number of arguments, types of arguments, and return type should match exactly (however, in covariant return types, you can provide the derived class of the return type in the overriding method).

You cannot overload methods that differ in return types alone. Similarly, you cannot overload methods that differ in exception specifications alone.

For an 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 finds more than one match, the overload resolution fails and the compiler issues an error.

Overloading is an example of static polymorphism (early binding) while overriding is an example of dynamic polymorphism (late binding).

You don’t need to do an explicit cast to perform an upcast. An upcast will always succeed.

You need to do an explicit cast to perform a downcast. A downcast may fail. You can use the instanceof operator to see if a downcast is valid.

A static import only imports static members of the specified package or class.

Chapter 4: Advanced Class Design

The abstract keyword can be applied to a class or a method but not to a field.

An abstract class cannot be instantiated. You can, however, create reference variables of an abstract class type.

An abstract class can extend another abstract class or can implement an interface. Further, an abstract class can be derived from a concrete class (though it is not a good practice)!

An abstract class need not declare an abstract method, which means it is not necessary for an abstract class to have methods declared as abstract. However, if a class has an abstract method, it should be declared as an abstract class.

A concrete subclass of an abstract class needs to provide implementation of all the abstract methods it inherits; otherwise you need to declare that subclass as an abstract class.

An abstract class may have methods or fields declared static. A final class is a non-inheritable class (i.e., you cannot inherit from a final class).

A final method is a non-overridable method (i.e., subclasses cannot override a final method).

All methods of a final class are implicitly final (i.e., non-overridable).

A final variable must be initialized. If it’s not initialized when it is declared, it must be initialized in all the constructors. Also, a final variable can be assigned only once.

The keyword final can be used for parameters. The value of a final parameter cannot be changed once assigned. Here, it is important to note that the value is implicitly understood for primitive types. However, the value for an object refers to the object reference, not its state. Therefore, you can change the internal state of the passed final object, but you cannot change the reference itself.

All static members do not require an instance of its class to call/access them. You can directly call/access them using the class name.

487

Chapter 15 OCPJP 7 Quick Refresher

A static member can call/access only a static member of its own class.

A static method cannot use the this or super keyword in its body.

Java supports four types of nested classes: static nested classes, inner classes, local inner classes, and anonymous inner classes.

Static nested classes may have static members, whereas the other flavors of nested classes may not.

Static nested classes and inner classes can access members of an outer class (even private members). However, static nested classes can access only static members of the outer class.

Local classes (both local inner classes and anonymous inner classes) can access all variables declared in the outer scope (whether a method, constructor, or a statement block).

You cannot use new with enums, even inside the enum definition.

Enums are implicitly declared public, static, and final, which means you cannot extend them.

When you define an enumeration, it implicitly inherits from java.lang.Enum. Internally, enumerations are converted to classes. Further, enumeration constants are instances of the enumeration class for which the enumeration constants are declared as members.

If you declare an enum within a class, then it is by default static.

You can compare two enumerations for equality using the == operator. When an enumeration constant’s toString() method is invoked, it prints the name of the enumeration constant.

Chapter 5: Object-Oriented Design Principles

An interface can extend another interface. Use the extends (and not the implements) keyword for this.

All methods declared in an interface are implicitly considered to be abstract.

Interfaces cannot contain instance variables. If you declare a data member in an interface, it should be initialized, and all such data members are implicitly treated as public static final members.

An interface cannot declare static methods. It can only declare instance methods.

You cannot declare members as protected or private in an interface. Only public access is allowed for members of an interface.

All methods declared in an interface are implicitly considered to be abstract. You can, however, explicitly use the abstract qualifier for the method.

An interface can be declared with an empty body (i.e., an interface without any members; these interfaces are known as tagging interfaces or marker interfaces). Such interfaces are useful for defining a common parent, so that runtime polymorphism can be used. For example, java.util defines the interface EventListener without a body.

An interface can be declared within another interface or class. Such interfaces are known as nested interfaces.

Unlike top-level interfaces that can have only public or default access, a nested interface can be declared as public, protected, or private.

Inheritance implies is-a, interface implies is-like-a, and composition implies has-a relationships.

488

f

Chapter 15 OCPJP 7 Quick Refresher

Favor composition over inheritance wherever feasible.

The Singleton design pattern ensures that only one instance of the class is created.

Making sure that an intended singleton implementation is indeed singleton is a non-trivial task, especially in a multi-threaded environment.

The factory design pattern “manufactures” the required type of product on demand.

You should consider using the abstract factory design pattern when you have a family of objects to be created.

A DAO design pattern essentially separates your core business logic from your persistence logic.

In a DAO pattern, you may also employ the abstract factory design pattern if you have multiple DAO objects and you have multiple persistence mechanisms.

Chapter 6: Generics and Collections

Generics will ensure that any attempts to mix elements of types other than the specified type(s) will be caught at compile time itself. Hence, generics offer type safety over using the

Object type.

Java 7 has introduced the “diamond” syntax where the type parameters (given after new operator and class name) can be omitted. The compiler will infer the types from the type declaration.

Generics are not covariant. That is, subtyping doesn’t work with generics. You cannot assign a derived generic type parameter to a base type parameter.

The <?> specifies an unknown type in generics and is known as a wildcard. For example, List<?> refers to a list of unknown type values.

Wildcards can be bounded. For example, <? extends Runnable> specifies that ? can match

any type as long as it is Runnable or any of its derived types. Note that both extends and super in this context are inclusive clauses, so you can replace X in <? extends X> and <? super X>.

Use the extends keyword for both class type and interface when specifying bounded types in generics. For specifying multiple base types, use the & symbol. For example, in List<?

extends X & Y>, ? will match types, extending both the types X and Y.

In general, when you use wildcard parameters, you cannot call methods that modify the object. If you try to modify, the compiler will give error messages. However, you can call methods that access the object.

The terms Collection, Collections, and collection are different. Collection— java.util. Collection<E>—is the root interface in the collection hierarchy. Collections—java.util. Collections—is a utility class that contains only static methods. The general term collection(s) refers to containers like map, stack, queue, etc.

It’s possible to define or declare generic methods in an interface or a class even if the class or the interface is not generic.

A generic class used without its type arguments is known as a raw type. Of course, raw types are not type safe. Java supports raw types so that it is possible to use the generic type in code that is older than Java 5 (note that generics were introduced in Java 5). The compiler

generates a warning when you use raw types in your code. You may use @SuppressWarnings({ "unchecked" }) to suppress the warning associated with raw types.

489

Chapter 15 OCPJP 7 Quick Refresher

List<?> is a supertype of any List type, which means you can pass List<Integer>, or

List<String>, or even List<Object> where List<?> is expected.

Implementation of generics is static in nature, which means that the Java compiler interprets the generics specified in the source code and replaces the generic code with concrete types. This is referred to as type erasure. After compilation, the code looks similar to what a developer would have written with concrete types. Essentially, the use of generics offers two advantages: first, it introduces an abstraction that enables you to write generic implementation; second, it allows you to write generic implementation with type safety.

There are many limitations of generic types due to type erasure. A few important ones are the following:

You cannot instantiate a generic type using a new operator. For example, assuming mem is a field, the following statement will result in a compiler error:

T mem = new T(); // wrong usage - compiler error 

You cannot instantiate an array of a generic type. For example, assuming mem is a field, the following statement will result in a compiler error: 

T[] amem = new T[100]; // wrong usage - compiler error 

You can declare non-static fields of type T, but not of static fields of type T. For example, class X<T> {

T instanceMem; // okay

 

static T statMem;

// wrong usage - compiler error

} 

It is not possible to have generic exception classes. For example, the following will not compile: 

class GenericException<T> extends Throwable { } // wrong usage - compiler error 

You cannot instantiate a generic type with primitive types. For example, List<int> will elicit a compiler error. However, you can use boxed primitive types.

The methods hashCode() and equals() need to be consistent for a class. For practical purposes, ensure that you follow this rule: the hashCode() method should return the same hash value for two objects if the equals() method returns true for them.

If you’re using an object in containers like HashSet or HashMap, make sure you override the hashCode() and equals() methods correctly.

In containers, it is not recommended that you store null as an argument since it could be difficult to understand the behavior of methods that return null. For example, there are methods in the Deque interface that return null, and it would be difficult for you to distinguish if the method successfully returned the element value null, or if the method failed and returned null.

The Figure 15-1 shows important interfaces belonging to the java.util package.

490

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