Download Writing Generic classes and methods Overloading and Overriding

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Further Object-Oriented Programming
Lecture 11
Writing Generic classes and methods
Overloading and Overriding
Prof. Dr. Igor Trajkovski
Faculty of Computer Science and IT
New York University Skopje
[email protected]
1
Review and Objectives
Last lecture we
•
introduced generics and consider how they are used in collections
•
looked at how to use some collections
•
discussed why it is important to override equals() and hashCode()
•
examined the Comparable and Comparator interfaces and saw how they can
be used to order a collection
•
investigated some useful static methods of the Collections class
Today we will
•
look at how to write our own generic classes and methods
•
discuss method overloading and overriding
2
Another look at generics
consider the implementation of
ArrayList in Java 5
java.util.ArrayList<E>
+ArrayList()
• <E> is the formal generic type
+add(o: E) : void
+add(index: int, o: E) : void
• this must be replaced by an actual
concrete type when an ArrayList
variable is declared
• the type could be String, Person,
or any reference type
• the same type E is used for some
method parameters and return
values
+clear(): void
+contains(o: Object): boolean
+get(index: int) : E
+indexOf(o: Object) : int
+isEmpty(): boolean
+lastIndexOf(o: Object) : int
+remove(o: Object): boolean
+size(): int
+remove(index: int) : boolean
• the get() method of an
ArrayList<String> returns a String
+set(index: int, o: E) : E
3
Writing generic classes
generics are widely used in the Java Collections Framework
• so the collections can safely hold any type of object
you can write your own generic classes
• for example a class to implement a queue using an ArrayList
public class MyQueue <T> {
private ArrayList<T> theList;
public MyQueue() {
theList = new ArrayList<T>();
}
// adds an element to the back of the queue
public boolean offer(T element) {
theList.add(element);
return true;
}
4
Writing generic methods
an individual method in a class can be generic
public class Test {
public static <T> boolean different(T o1, T o2) {
if (!o1.equals(o2))
return true;
return false;
}
this method will only accept two objects of type T
• or subtypes of T
invoke it using the <type> before the method name
Test.<String>different(“Cathy”, “Piano”);
what if we want to ensure it only accepts objects which
• are instances of Person or its subtypes?
• implement the Comparable interface?
5
Writing generic methods
public static <T extends Person> boolean different(T o1, T o2) {
if (!o1.equals(o2))
return true;
return false;
}
here T can be Person, or any of its subtypes
public static <T extends Comparable> T largest(T o1, T o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
notice the keyword is extends, even though here it means “type T which
implements the Comparable interface”
6
Overloading and overriding
• we have already seen these concepts when discussing inheritance and
polymorphism
• a derived class (subclass) can override a base class (superclass)
member method
• by providing a new method with the same name and signature as the
original method
• a class (and/or its subclasses) can have more than one method with
the same name
• provided they have different parameter lists
• overloading
• when overriding a base class method in a derived class, the argument
list must exactly match the method to be overridden
• otherwise you’re not overriding the base class method
• instead you are defining a new overload in the derived class
7
Accessibility and Overriding
• the overriding method must be at least as accessible as the base
class method
• consider class Person with a public printDetails method
• class Student which extends Person overrides printDetails
• Person p1 = new Student();
• p1.printDetails();
• the Student version of printDetails must also be public
• otherwise how could polymorphism work?
• the access level CAN be less restrictive
• for example, a protected method in the base class can be
overridden by a public method in the derived class
8
What methods can be overridden?
• only methods which are inherited by the subclass can be overridden
• private methods cannot be overridden
• the subclass has no access to them
• package (default) access methods cannot be overridden by a subclass
in a different package
• but protected methods can
• static methods cannot be overridden
• but they can be redefined in a subclass (see next slide)
• methods marked final cannot be overridden
9
Redefining static methods
what is the output of the following code?
class Superclass {
public static String aMethod() {
return "super";
}
}
class Subclass extends Superclass {
public static String aMethod() {
return "sub";
}
}
public class Test {
public static void main(String args[]) {
Superclass A = new Superclass();
System.out.println(A.aMethod());
Subclass B = new Subclass();
System.out.println(B.aMethod());
Superclass C = new Subclass();
System.out.println(C.aMethod());
}
}
10
Output
super
sub
super
the version invoked depends on the type of the reference
• not the type of the actual object
• remember static methods belong to the class, not the object
A.aMethod() is equivalent to Superclass.aMethod();
if aMethod were not static, it would be called polymorphically and
output would be
super
sub
sub
11
Return types in overridden methods
• when overriding a method, the return type must be the same as
the return type of the original method
• OR it can be a sub-type of the original return type
• this is called a co-variant return
• first allowed in Java 1.5 (Java 1.4 won’t compile)
class A {
public Person getPerson() { return new Person(); }
}
class B extends A
{
public Student getPerson() { return new Student();}
}
• why is this allowed?
12
Overriding methods that throw exceptions
• a method that overrides another method cannot throw any new
checked exceptions
• any checked exceptions must be declared in the base class, so the
calling method knows it must handle them
• new unchecked exceptions can be thrown
• like any unchecked exception, these do not have to be handled
• the overriding method can throw fewer exceptions than the base
class method
• if the overriding method will not generate an exception there is no
need to declare one
• we will consider exceptions in more detail next lecture
13
The Java collections framework
AbstractList
• the add method in AbstractList throws an
exception
public void add(int index, E element) {
throw new UnsupportedOperationException();
ArrayList
}
• in the subclass ArrayList this method is
overridden and does not throw the exception
public boolean add(E e) {
ensureCapacity(size + 1);
elementData[size++] = e;
return true;
}
14
Overloading methods
• overloaded methods have the same name but different parameter lists
• number and / or types of parameters
• the return type can be different
• the access modifier can be different
• overloaded methods can throw new or different exceptions
• the set of overloaded methods should do similar things!
public int addNums(int num1, int num2)
{ return num1 + num2;}
protected double addNums(double x, double y)
{
return x + y; }
15
Which overloaded method is invoked?
• the one with the matching parameter list
int result = addNums(5, 6);
double answer = addNums(5.2, 6.3);
• if an exact match is not available the compiler will look for the
closest compatible match
public class Example {
public static void main(String[] args) {
int num1 = 5;
int num2 = 6;
double answer = addNums(num1, num2);
}
protected double addNums(double x, double y)
{
return x + y; }
}
16
What about object references?
public static void aMethod(Person p) {
System.out.println("Person overload " + p.toString());
}
public static void aMethod(Student s) {
System.out.println("Student overload " + s.toString());
}
assuming Student extends Person, which method is called?
Person p1 = new Person();
Person p2 = new Student();
Student s = new Student();
aMethod(p1);
aMethod(p2);
aMethod(s);
17
Output
• Person overload Person@187aeca
• Person overload Student@e48e1b
• Student overload Student@12dacd1
which method to call is decided at compile time
• based on the type of the object reference(s) passed as method
argument(s)
this is unlike the situation when a method is overridden
• which method to call is decided at run time
• based on the type of the object on which the method is called
18
Wrapper classes
• each Java primitive type has a corresponding wrapper class
• Boolean
• Byte
• Character
• Double
• Float
• Integer
• Long
• Short
• they all implement Comparable
• the numeric wrapper classes extend Number
19
Wrapper classes
• all wrapper classes except Character have two constructors
• one that takes the primitive type
• one that take a String
Integer x = new Integer(60);
Integer y = new Integer(“60”);
– useful for getting input from a GUI
• the static method valueOf takes a String and returns a wrapper
object
Integer z = Integer.valueOf(“60”);
• the static method parseXXX (parseInt, parseDouble etc) takes a
String and returns the appropriate primitive
int xx = Integer.parseInt(“60”);
• another useful method for getting input from GUIs
20
Autoboxing (boxing and unboxing)
From Java 5, the compiler will automatically
•
construct a wrapper object from a primitive (boxing)
•
extract a primitive from a wrapper object (unboxing)
when required
for example
Integer x = new Integer(42);
x++;
is equivalent to
Integer x = new Integer(42);
int x1 = x.intValue();
x1++;
x = new Integer(x1);
x
is a reference to an Integer object throughout but the object is unwrapped to
extract the primitive integer, and re-wrapped as required
21
Which overloaded method is invoked?
public class Overloading {
public static void main(String[] args) {
int num1= 5;
Integer num2 = new Integer(6);
aMethod(num1);
aMethod(num2);
}
public static void aMethod(int num) { System.out.println("int");};
public static void aMethod(Integer num) {System.out.println("Integer");}
public static void aMethod(double num) { System.out.println("double");};
}
Output: int
Integer
the method with matching parameter list is invoked
22
What if only one method is available?
public class Overloading {
public static void main(String[] args) {
int num1= 5;
Integer num2 = new Integer(6);
aMethod(num1);
aMethod(num2);
}
public static void aMethod(int num) { System.out.println("int");}
}
Output: int
int
num2 is unboxed to match the int type required
23
What if only one method is available?
public class Overloading {
public static void main(String[] args) {
int num1= 5;
Integer num2 = new Integer(6);
aMethod(num1);
aMethod(num2);
}
public static void aMethod(Integer num) { System.out.println("Integer"); };
}
Output: Integer
Integer
num1 is autoboxed to match the Integer type required
24
What about this?
public class Overloading {
public static void main(String[] args) {
int num1= 5;
Integer num2 = new Integer(6);
aMethod(num1);
aMethod(num2);
}
public static void aMethod(double num) { System.out.println("double");};
}
Output: double
double
num1 is widened to a double
num2 is unboxed then widened to a double
25
Be careful when calling overloaded methods
• if an exact match of a primitive to the parameter list is not
available, the compiler will attempt to widen the parameter
• int to long or float or double
• the type nearest in size will be used
• if this does not produce a match, autoboxing will be attempted
• int to Integer
• references to objects can also be widened
• if the exact type is not in the parameter list, look for the supertype
• polymorphism Student to Person or Object
• as the set of overloaded methods should all have the same effect,
this should not be a problem!
26
Summary
today we have discussed
• writing our own generic classes and methods
• rules for overriding methods
• rules for overloading methods
• wrapper classes for primitive types
• autoboxing and its consequences for overloaded methods
we will look at some examples in next week’s tutorial
Further reading:
• Generics:
– Liang Chapter 21
– Sun Java tutorial - Learning the Java language: Generics
• Wrapper classes
– Liang 11.9, 11.11
– Sun Java tutorial - Numbers and Strings: the Number class
27