2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
-
Upload
morgan-booth -
Category
Documents
-
view
220 -
download
0
description
Transcript of 2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
1
2005 Pearson Education, Inc. All rights reserved.
Classes and Objects: A Deeper
Look
2
2005 Pearson Education, Inc. All rights reserved.
Overloaded vs. Overridden methods
Can you tell me the difference(s) between
overloaded and overridden methods in
Java?
overload overidden
3
2005 Pearson Education, Inc. All rights reserved.
Method Overloading Method overloading
Multiple methods with the same name, but different types, number or order of
parameters in their parameter lists
Compiler decides which method is being called by
matching the method call’s argument list to one of the
overloaded methods’ parameter lists
A method’s name and number, type and order of its parameters form its signature
4
2005 Pearson Education, Inc. All rights reserved.
Method Overloading
Differences in return type are irrelevant in method overloading
Overloaded methods can have different return types
Methods with different return types but the same signature cause a compilation error
5
2005 Pearson Education, Inc. All rights reserved.
Overloaded Methods
Methods can share the same name as long asthey have a different number of parameters (Rule 1) their parameters are of different data types when the
number of parameters is the same (Rule 2)
public void myMethod(int x, int y) { ... }
public void myMethod(int x) { ... }
public void myMethod(double x) { ... }
public void myMethod(int x) { ... }
Rule 1
Rule 2
2005 Pearson Education Inc. All rights reserved.
If a class does not define a constructor,a. the compiler will provide a default constructorb. We will get a compiler-time errorc. We will get a run-time errord. No error but program may not run correctly
What happen if
7
2005 Pearson Education Inc. All rights reserved.
What happen if
If a class does not define a constructor,a. the compiler will provide a default constructorb. We will get a compiler-time errorc. We will get a run-time errord. No error but program may not run correctly
8
2005 Pearson Education Inc. All rights reserved.
Default and No-Argument Constructors
Every class must have at least one constructor— If no constructors are declared, the compiler will create a
default constructor
•Takes no arguments and initializes data members (instance variables) to their initial values specified in their declaration or to their default values
•Default values are zero for primitive numeric types, false for boolean values and null for references
— If constructors are declared, the default initialization for objects of the class will be performed by a no-argument constructor (if one is declared)
9
2005 Pearson Education Inc. All rights reserved.
Overloaded Constructors
Overloaded constructors— Provide multiple constructor definitions with different
signatures— full signature of a method is a list containing the method
name followed by the name of the data type for each parameter of the method.
No-argument constructor— A constructor invoked without arguments
10
2005 Pearson Education Inc. All rights reserved.
Overloaded ConstructorThe same rules apply for overloaded constructors
— this is how we can define more than one constructor to a class
public Person( ) { ... }
public Person(int age) { ... }
public Pet(int age) { ... }
public Pet(String name) { ... }
Rule 1
Rule 2
11
2005 Pearson Education Inc. All rights reserved.
Example
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Some initialization going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Some initi }
}
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Initialization is going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Initialization is going on here }}
12
2005 Pearson Education Inc. All rights reserved.
Example
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Some initialization going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Some initi }
}
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() {
}
// constructor with a size argument public TestList (int size) {
// Initialization is going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Initialization is going on here }}
13
2005 Pearson Education Inc. All rights reserved.
Example
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Some initialization going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Some initi }
}
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() {
}
// constructor with a size argument public TestList(int size) {
// Initialization is going on here }
// constructor with a prior String data public TestList (String[ ] givenData) { // Initialization is going on here }}
14
2005 Pearson Education Inc. All rights reserved.
Example
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Some initialization going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Some initi }
}
public class TestList { // data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" }; // empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Initialization is going on here } // constructor with a prior String data public TestList(String[ ] givenData) { // Initialization is going on here } // Is this right? public TestList (int maxsize) { // Initialization is going on here }}
15
2005 Pearson Education Inc. All rights reserved.
Controlling Access to Members
public method: a service the class provides to the class’s clientsprivate data members and private methods are not accessible to the class’s clients
16
2005 Pearson Education Inc. All rights reserved.
Example
class Service { public int memberOne; private int memberTwo;
public void doOne() {
…
} private void doTwo() {
…
}
}
…
Service obj = new Service();
obj.memberOne = 10;
obj.memberTwo = 20;
obj.doOne();
obj.doTwo();
…
Client Service
17
2005 Pearson Education Inc. All rights reserved.
Clients are neither aware of, nor involved in, a class’s implementation. Clients generally care about what the class does but not how the class does it.
18
2005 Pearson Education Inc. All rights reserved.
Local, Parameter & Data Member
An identifier appearing inside a method can be a local variable, a parameter, or a data member.The rules are
— If there’s a matching local variable declaration or a parameter, then the identifier refers to the local variable or the parameter.
— Otherwise, if there’s a matching data member declaration, then the identifier refers to the data member.
— Otherwise, it is an error because there’s no matching declaration.
19
2005 Pearson Education Inc. All rights reserved.
Example
public class TestList {
// data members String [] data = { "Do", "Re", "Mi", "Fa", "So", "La", "Ti", "Do" };
// empty constructor public TestList() { }
// constructor with a size argument public TestList(int size) {
// Some initialization going on here }
// constructor with a prior String data public TestList(String[] givenData) { // Some initi }
}
public class TestList { // data members
int size; // empty constructor public TestList() { }
// constructor with a size argument public TestList (int size) {
this.size = size;}
}
20
2005 Pearson Education Inc. All rights reserved.
Common ErrorIt is often a logic error when a method contains a parameter or local variable that has the same name as a field of the class. In this case, use reference this if you wish to access the field of the class—otherwise, the method parameter or local variable will be referenced.
Avoid method parameter names or local variable names that conflict with field names. This helps prevent subtle, hard-to-locate bugs.
21
2005 Pearson Education Inc. All rights reserved.
Data Abstraction and Encapsulation
Data abstraction— Information hiding
•Classes normally hide the details of their implementation from their clients
— Abstract data types (ADTs)
•Data representation– example: primitive type int is an
abstract representation of an integer• ints are only approximations of
integers, can produce arithmetic overflow
•Operations that can be performed on data
22
2005 Pearson Education Inc. All rights reserved.
Creating Packages
To declare a reusable class— Declare a public class— Add a package declaration to the source-code file
•must be the very first executable statement in the file
•package name should consist of your Internet domain name in reverse order followed by other names for the package– example: com.deitel.jhtp6.ch08– package name is part of the fully
qualified class name• Distinguishes between multiple classes
with the same name belonging to different packages
• Prevents name conflict (also called name collision)
– Class name without package name is the simple name
23
2005 Pearson Education Inc. All rights reserved.
— Compile the class so that it is placed in the appropriate package directory structure
•Example: our package should be in the directory
projects
project2
javac command-line option –d– javac creates appropriate directories
based on the class’s package declaration
– A period (.) after –d represents the current directory
Creating Packages
24
2005 Pearson Education Inc. All rights reserved.
8.16 Time Class Case Study: Creating Packages (Cont.)
— Import the reusable class into a program
•Single-type-import declaration– Imports a single class– Example: import java.util.Random;
•Type-import-on-demand declaration– Imports all classes in a package– Example: import java.util.*;
Creating Packages
25
2005 Pearson Education Inc. All rights reserved.
Class loader— Locates classes that the compiler needs
•First searches standard Java classes bundled with the JDK
•Then searches for optional packages– These are enabled by Java’s extension
mechanism•Finally searches the classpath
– List of directories or archive files separated by directory separators• These files normally end with .jar
or .zip• Standard classes are in the archive
file rt.jar
26
2005 Pearson Education Inc. All rights reserved.
To use a classpath other than the current directory— -classpath option for the javac compiler— Set the CLASSPATH environment variable
The JVM must locate classes just as the compiler does
— The java command can use other classpathes by using the same techniques that the javac command uses
27
2005 Pearson Education Inc. All rights reserved.
Visibility— Attributes normally should be private, methods invoked
by clients should be public— Visibility markers in UML
•A plus sign (+) indicates public visibility•A minus sign (-) indicates private visibility
Navigability— Navigability arrows indicate in which direction an
association can be traversed— Bidirectional navigability
•Associations with navigability arrows at both ends or no navigability arrows at all can be traversed in either direction
28
2005 Pearson Education Inc. All rights reserved.
9
Object-Oriented Programming: Inheritance
29
2005 Pearson Education Inc. All rights reserved.
What should we do?We are asked to develop two classes for
undergraduate and graduate students
Solution 1: We can define two unrelated
classes, one for undergraduates and one for graduates.
Solution 2:We can model the two kinds of
students by using classes that are related in an inheritance hierarchy.
30
2005 Pearson Education Inc. All rights reserved.
We design three classes:— Student— UndergraduateStudent— GraduateStudent
The Student class will incorporate behavior and data common to both UndergraduateStudent and GraduateStudent objects.
The UndergraduateStudent class and the GraduateStudent class will each contain behaviors and data specific to their respective objects.
What should we do?
31
2005 Pearson Education Inc. All rights reserved.
Inheritance Hierarchy
32
2005 Pearson Education Inc. All rights reserved.
The Protected Modifier
The modifier protected makes a data member or method visible and accessible to the instances of the class and the descendant classes.
Public data members and methods are accessible to everyone.
Private data members and methods are accessible only to instances of the class.
33
2005 Pearson Education Inc. All rights reserved.
Introduction
Inheritance— Software reusability— Create new class from existing class
•Absorb existing class’s data and behaviors•Enhance with new capabilities
— Subclass extends superclass
•Subclass– More specialized group of objects– Behaviors inherited from superclass
• Can customize– Additional behaviors
34
2005 Pearson Education Inc. All rights reserved.
Introduction (Cont.)
Class hierarchy— Direct superclass
• Inherited explicitly (one level up hierarchy)— Indirect superclass
• Inherited two or more levels up hierarchy— Single inheritance
• Inherits from one superclass— Multiple inheritance
• Inherits from multiple superclasses– Java does not support multiple
inheritance
35
2005 Pearson Education Inc. All rights reserved.
Inheritance examples.
Superclass Subclasses Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan,
MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount, SavingsAccount
36
2005 Pearson Education Inc. All rights reserved.
Inheritance hierarchy— Inheritance relationships: tree-like hierarchy structure— Each class becomes
•superclass– Supply members to other classes
OR•subclass
– Inherit members from other classes
37
2005 Pearson Education Inc. All rights reserved.
Inheritance hierarchy for university CommunityMembers
38
2005 Pearson Education Inc. All rights reserved.
Inheritance hierarchy for Shapes.
39
2005 Pearson Education Inc. All rights reserved.
Inheritance and Member Accessibility
40
2005 Pearson Education Inc. All rights reserved.
The Effect of Three Visibility Modifiers
41
2005 Pearson Education Inc. All rights reserved.
Accessibility of Super from Sub
Everything except the private members of the Super class is visible from a method of the Sub class.
42
2005 Pearson Education Inc. All rights reserved.
Accessibility from Another Instance
Data members accessible from an instance are also accessible from other instances of the same class.
43
2005 Pearson Education Inc. All rights reserved.
Inheritance and Constructors
Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses.You must define a constructor for a class or use the default constructor added by the compiler.The statement super();
calls the superclass’s constructor.If the class declaration does not explicitly designate the superclass with the extends clause, then the class’s superclass is the Object class.
44
2005 Pearson Education Inc. All rights reserved.
Abstract Superclasses and Abstract Methods
When we define a superclass, we often do not need to create any instances of the superclass.Depending on whether we need to create instances of the superclass, we must define the class differently.
45
2005 Pearson Education Inc. All rights reserved.
Definition: Abstract Class
An abstract class is a class — defined with the modifier abstract OR— that contains an abstract method OR— that does not provide an implementation of an inherited
abstract method
An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body.
— Private methods and static methods may not be declared abstract.
No instances can be created from an abstract class.