0% found this document useful (0 votes)
17 views

Lecture 4

The document discusses inheritance and polymorphism in object-oriented programming. It covers instance variables and methods, static variables and methods, scope of variables, the Object class, and wrapper classes. Static members have only one copy regardless of instances and can be accessed via the class name, while instance members are unique to each object.

Uploaded by

Waley Lin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lecture 4

The document discusses inheritance and polymorphism in object-oriented programming. It covers instance variables and methods, static variables and methods, scope of variables, the Object class, and wrapper classes. Static members have only one copy regardless of instances and can be accessed via the class name, while instance members are unique to each object.

Uploaded by

Waley Lin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

COMP 212 –

Programming II
2 – Inheritance and
Polymorphism(2)

1
2– Inheritance and Polymorphism-
Outline
Instance Variables and Methods

Static Variables, Constants, Methods

Scope of Variables

The Object Class

Wrapper Classes

2
Instance Instance variables
Variables, belong to a specific
instance.
and Instance methods are
Methods invoked by an instance
of the class.

3
 Static
members/methods
Static have only one copy
regardless of how
Variables, many instances are
Constants, created so a static
variable
and  A static method can
Methods be invoked without
the need for creating
an instance of a class

4
 Static variables are
shared by all the
instances of the
Static class.
Variables,  Static methods are
Constants, not tied to a specific
object.
and
 Static constants are
Methods final variables shared
by all the instances
of the class.

5
To declare static
Static variables, constants,
and methods, use the
Variables, static modifier.
Constants, A variable or method
and that is not dependent
on a specific instance
Methods, of the class should be a
cont. static variable or
method.

6
Example of Using Instance and
Class Variables and Method

Circle3 Example Code of Chapter 1:

Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObject(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

7
Static Variables, Constants,
and Methods, cont.

instantiate Memory
circle1

radius = 1 1 radius After two Circle


Circle numberOfObjects = 2 objects were created,
numberOfObjects
radius: double is 2.
numberOfObjects: int
2 numberOfObjects
getNumberOfObjects(): int
+getArea(): double instantiate circle2

radius = 5 5 radius
UML Notation: numberOfObjects = 2
+: public variables or methods
underline: static variables or methods

8
Since static variables and methods do not
Static belong to any instance:

Variables, Use ClassName.methodName(arguments) to


invoke a static method and
Constants, ClassName.staticVariable to access a static
variable.
and NOTE: the ClassName, not the ObjectName

Methods, Instance variables and methods can be


used ONLY from instance methods, not from
cont. static methods.

9
Static Variables, Constants,
and Methods, cont.
What’s wrong with the code below?
public class Foo {
int i=5;
static int k=2;
public static void main(String[] args) {
int j=i;
m1();
}
public void m1() {
i = i + k + m2(i,k);
}
public static int m2(int i, int j) {
return (int) (Math.pow(i,j));
}
}
10
Static Variables, Constants,
and Methods, cont.
What’s wrong with the code below?
public class Foo {
int i=5;
static int k=2;
public static void main(String[] args) {
// ERROR: non-static variable i cannot be referenced from a static context
int j=i;
m1();
}
public void m1() {
i = i + k + m2(i,k);
}
public static int m2(int i, int j) {
return (int) (Math.pow(i,j));
}
} 11
Given the following class:
public class F {
static int j;

Static double d;
void xmethod() {

Variables, }
static void ymethod() {

Constants, }
}

and Which statement(s) below are correct? Assume f is an


instance of class F

Methods, 1.

2.
f.d = f.j;
f.j = (int) f.d;

cont. 3.

4.
F.d = F.j;
F.j = (int) F.d;
5. F.xmethod();
6. F.ymethod();

12
Given the following class:
public class F {
static int j;

Static double d;
void xmethod() {

Variables, }
static void ymethod() {

Constants, }
}

and Which statement(s) below are correct? Assume f is an


instance of class F

Methods, 1.

2.
f.d = f.j;
f.j = (int) f.d;

cont. 3.

4.
F.d = F.j;
F.j = (int) F.d;
5. F.xmethod();
6. F.ymethod();

13
The scope of instance and
static variables is the entire
class. They can be declared
anywhere inside a class.
Scope of The scope of a local variable
starts from its declaration and
Variables continues to the end of the
block that contains the variable.
A local variable must be
initialized explicitly before it
can be used.

14
The Object Class - Method
common to all objects
 Although Object is a concrete class, it is designed primarily for
extension.
 All of its non-final methods have explicit general contracts because they
are designed to be overridden.
protected Object clone() throws CloneNotSupportedException
public boolean equals(Object obj)
public int hashCode()
public String toString()
 It is the responsibility of any class overriding these methods to obey
their general contracts; failure to do so will prevent other classes that
depend on the contracts (such as HashMap and HashSet) from
functioning properly in conjunction with the class.

15
Two kinds of object equality

 Often in Java programs you need to compare two


objects to determine if they are equal or not. It turns
out there are two different kinds of equality one can
determine about objects in Java, reference equality or
logical equality.
 The equality operator (==) compares the references
(addresses in memory) of the two variables- this is
known as reference equality.
 Logical equality compares the data of the objects
instead of the value of the references.

16
When not to override equals

 The equals method for class Object implements the most


discriminating possible equivalence relation on objects; that is, for
any non-null reference values x and y, this method returns true if
and only if x and y refer to the same object.
 Overriding the equals method seems simple, but there are many
ways to get it wrong. The easiest way to avoid problems is not to
override the equals method:
 When we don’t care whether the class provides a “content
equality” test.
 When a superclass has already overridden equals, and the superclass
behavior is appropriate for this class.
 When the class is private or package-private, and you are certain that
its equals method will never be invoked.

17
Override the equals method

 The equals() method compares  The equals() method accepts


the references (addresses in both:
memory) of the two variables-
this is known as reference public boolean equals(Object obj) {
equality: if (this == obj) return true;
else if (o instanceof Circle) {
public boolean equals(Object obj) { return radius == ((Circle)o).radius;
return (this == obj); }
} else return false;
}
 The equals() method compares
the data of the objects instead
of the value of the references:

public boolean equals(Object o) {


if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else return false;
}
18
Always override toString

 Providing a good toString implementation makes your


class much more pleasant to use.
 The toString method is automatically invoked when an
object is passed to println, printf, the string
concatenation operator, or assert, or printed by
a debugger.
 When practical, the toString method should return all of
the interesting information contained in the object.
 Provide programmatic access to all of the information
contained in the value returned by toString. If you fail
to do this, you force programmers who need this
information to parse the string.
19
The Wrapper Classes

 Many Java methods require the use of objects


as arguments.
 Java offers a convenient way to wrap a primitive data
type into an object (e.g. wrapping int into Integer)
 By using a wrapper class, you can process primitive data
type values as objects.

20
Need of Wrapper Classes

 They convert primitive data types into objects. Objects


are needed if we wish to modify the arguments passed
into a method (because primitive types are passed by
value).
 The classes in java.util package handles only objects
and hence wrapper classes help in this case also.
 Data structures in the Collection framework, such as
ArrayList and Vector, store only objects (reference
types) and not primitive types.
 An object is needed to support synchronization in
multithreading.
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
21
The Wrapper Classes

Boolean Integer
Character Long
Short Float
Byte Double
 NOTE: The wrapper classes do not have no-arg constructors.
 NOTE: The instances of all wrapper classes are immutable,
i.e., their internal values cannot be changed once the
objects are created.

22
The toString, equals, and
hashCode Methods
 Each wrapper class overrides
the toString(), equals(), and hashCode() methods
defined in the Object class.
 Since all the numeric wrapper classes and
the Character class
implement the Comparable interface,
the compareTo() method is implemented in these
classes.

23
The Integer and Double Classes
java.lang.Integer java.lang.Double
-value: int -value: double
+MAX_VALUE: int +MAX_VALUE: double
+MIN_VALUE: int +MIN_VALUE: double

+Integer(value: int) +Double(value: double)


+Integer(s: String) +Double(s: String)
+byteValue(): byte +byteValue(): byte
+shortValue(): short +shortValue(): short
+intValue(): int +intValue(): int
+longVlaue(): long +longVlaue(): long
+floatValue(): float +floatValue(): float
+doubleValue():double +doubleValue():double
+compareTo(o: Integer): int +compareTo(o: Double): int
+toString(): String +toString(): String
+valueOf(s: String): Integer +valueOf(s: String): Double
+valueOf(s: String, radix: int): Integer +valueOf(s: String, radix: int): Double
+parseInt(s: String): int +parseDouble(s: String): double
+parseInt(s: String, radix: int): int +parseDouble(s: String, radix: int): double

24
The Integer Class
and the Double Class

Class Constants
Conversion
Constructors MAX_VALUE,
Methods
MIN_VALUE

25
Numeric Wrapper Class
Constructors
 You can construct a wrapper object either from a
primitive data type value or from a string representing
the numeric value. The constructors for Integer and
Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)

26
Numeric Wrapper Class
Constants
 Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE.
 MAX_VALUE represents the maximum value of the corresponding
primitive data type.
 For Byte, Short, Integer, and Long, MIN_VALUE represents the
minimum byte, short, int, and long values.
 For Float and Double, MIN_VALUE represents the
minimum positive float and double values.
 The following statements display the maximum integer (2,147,483,647),
the minimum positive float (1.4E-45), and the maximum double floating-
point number (1.79769313486231570e+308d).
System.out.println(Integer.MAX_VALUE);
System.out.println(Float.MIN_VALUE);
System.out.println(Double.MAX_VALUE);
27
Conversion Methods

 Each numeric wrapper class implements the


abstract methods doubleValue, floatValue, intValue,
longValue, and shortValue, which are defined in
the Number class. These methods “convert” objects
into primitive type values.

28
The Static valueOf Methods

 The numeric wrapper classes have a useful class


method, valueOf(String s). This method creates a new
object initialized to the value represented by the
specified string. For example:

Double doubleObject = Double.valueOf("12.4");


Integer integerObject = Integer.valueOf("12");

29
Automatic Conversion
between Primitive Types and
Wrapper Class Types
 Converting a primitive value to a wrapper object is called
boxing. The reverse conversion is called unboxing. The
compiler will automatically box a primitive value that
appears in a context requiring an object, and will unbox an
object that appears in a context requiring a primitive
value.

Integer integerObject = new Integer(2);


Integer integerObject = 2; //auto-boxing

Integer IntObj = Integer.valueOf("34");


int primitiveInt = IntObj; //auto-unboxing

30
Consider implementing
Comparable
 Unlike the other methods discussed, the compareTo() method
is not declared in Object. Rather, it is the sole method in the
Comparable interface.
 By implementing Comparable, you allow your class to
interoperate with all of the many generic algorithms and
collection implementations that depend on this interface.
 If you are writing a value class with an obvious natural
ordering, such as alphabetical order, numerical order, or
chronological order, you should strongly consider
implementing the interface.
public interface Comparable 〈T 〉 {
int compareTo(T y)
}
 The compareTo() method compares this object with the
specified object for order and returns a negative integer,
zero, or a positive integer as this object is less than, equal
to, or greater than the specified object.
31
Contract of the compareTo
method
 x.compareTo(y) > 0 if and only if y.compareTo(x) < 0.
 x.compareTo(y) == 0 if and only if y.compareTo(x) == 0.
 (transitivity) x.compareTo(y) > 0 && y.compareTo(z) > 0 implies
x.compareTo(z) > 0.
 x.compareTo(y) == 0 implies that x.compareTo(z) agrees with
y.compareTo(z).
 It is strongly recommended, but not strictly required, that
(x.compareTo(y) == 0) == (x.equals(y)).

32
Example: compareTo method

public class Rational implements Comparable<Rational> {


private BigInteger num, denom;
...
@Override
public int compareTo(Rational y) {
return num.multiply(y.denom).compareTo(denom.multiply(y.num));
}
}

33

You might also like