CS计算机代考程序代写 Java c++ Chapter 2.

Chapter 2.
Class and Object
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
1

A Motivating Example
—Paul, the procedural programming guy, and Ocean, the OO guy, were told to develop a software based on the following specification
the spec
There will be shapes on a GUI, a square, a circle, and a triangle. When the user clicks on a shape, the shape will rotate clockwise 360o (i.e., all the way around) and play a mp3 sound file specific to that particular shape.
2

Procedural Approach
—Paul designed his software by asking himself —Whatarethetasksthisprogramhasto do?
— What procedures do we need?
—Paul identified and implemented the following 2 procedures
rotate(shapeNum) {
// make the shape rotate 360o
}
playSound(shapeNum) {
// use shapeNum to lookup which
// mp3 file to play, and play it
}
3

Object-Oriented Approach
—Ocean designed his software by asking himself — What are the things in this program?
— Who are the key players?
—Ocean identified the shapes being the key players and wrote a class for each of the 3 shapes
no need to have shapeNum as an argument!
Square
rotate() {
// code to rotate
// a square
}
playSound() {
// code to play the mp3
// file for a square
}
Circle
rotate() {
// code to rotate
// a circle
}
playSound() {
// code to play the mp3
// file for a circle
}
Triangle
rotate() {
// code to rotate
// a triangle
}
playSound() {
// code to play the mp3
// file for a triangle
}
4

Spec Change
—A “minor” change was made to the specification
There will be an amoeba shape on the screen, with the others. When the user clicks on the amoeba, it will rotate like others, and play a wav sound file.
What should be added to the spec?
5

Spec Change
—Paul needed to update his playSound() procedure
playSound(shapeNum) {
// if the shape is not an amoeba
// use shapeNum to lookup which // mp3 file to play, and play it
// else
// play amoeba wav file
}
Amoeba
rotate() {
// code to rotate
// an amoeba
}
playSound() {
// code to play the wav
// file for an amoeba
}
—Ocean just wrote a new class for an amoeba shape
6

Another Spec Change
—Another “minor” change was made to the specification
The amoeba shape should rotate around a specific point instead of the center of its bounding box like the other shapes do.
What should be added to the spec?
7

Another Spec Change
—Paul needed to update his rotate() procedure and introduce new arguments
—Ocean only needed to modify the rotate() method of his Amoebaclass and add two instance variables
rotate(shapeNum, x, y) {
// if the shape is not an amoeba // calculate the center point // then rotate
// else
// use the (x, y) as
// the point of rotation // then rotate
}
Amoeba
int x int y
rotate() {
// code to rotate
// an amoeba
}
playSound() {
// code to play the wav
// file for an amoeba
}
87

Procedural vs Object-Oriented
—Paul’s code (procedural approach)
— Making a minor change often involves touching
previously tested code
— Code is difficult to maintain because data and
procedures are separated —Ocean’s code (OO approach)
— Making a modification often does not involve touching previously tested code for other parts of the program
—Duplicate code (need to maintain 4 different rotate() methods)
Inheritance
is the solution!
9

Inheritance
—Identify the common features from the 4 different shape classes
—rotate()
— playSound()
Square
rotate() playSound( )
Circle
rotate() playSound( )
Triangle
rotate() playSound( )
Amoeba
rotate() playSound( )
10

Inheritance
—Abstract these common features out and put them in a new class called Shape
Shape
rotate() playSound( )
Square
Circle
Triangle
Amoeba
11

Inheritance
—Make the new Shape class the superclass of the 4 shape classes
Shape
rotate() playSound( )
superclass
Square
Circle
Triangle
Amoeba
subclasses
A subclass will automatically inherit all the properties
(both instance variables and methods) of its superclass 1211

Inheritance
—Make the Amoeba class override the rotate() and playSound() methods of its superclass
more abstract
Shape
rotate() playSound( )
Square
Circle
Triangle
Amoeba
rotate() {
// amoeba-specific // rotate code
}
playSound() {
// amoeba-specific // sound code
}
more specific
13

Some Advantages of OOP
— Modularity
— The code for an object can be written and maintained
independently of the code for other objects — Information hiding
— An object’s internal implementation remains hidden — Code re-use
— The code for an existing object can be reused either directly or through inheritance
— Pluggability
— Problematic objects can be replaced just like the way mechanical problems are being fixed in the real world
14

Classes and Objects
— Classes and objects are the basic building blocks in OOP
— A class is not an object, but a blueprint for an object
— It tells the virtual machine how
to make an object of that particular
type
— Each object made from that class (i.e.,
an instance of that class) is unique and has its own state — Example:
— The Button class can be used to make dozens of different buttons, and each button might have its own color, size, shape, label, etc.
15

Designing a Class
— When designing a class, think about the objects that will be created from that class type
— Objects can be used to model real world objects (e.g., car, dog), as well as concepts (e.g., date, bank account)
— Think about
— Things the object knows (state) — Things the object does (behavior)
knows knows
knows
ShoppingCart
cartContents
addItemToCart() removeItemFromCart() checkOut()
Button
label color
setColor( ) setLabel( ) press() release()
Alarm
alarmTime alarmMode
setAlarmTime( ) setAlarmMode( ) snooze()
does does does
16

Instance Variables and Methods
— Objects have instance variables and methods, which are designed as part of the class
— Instance Variables
—Things an object knows about itself
—Represent an object’s state (data)
—Can have unique values for each object of that type
— Methods
—Things an object can do —Define the behavior of an object —Operate on data of an object
instance variables (state)
methods (behavior)
label color
Button
setColor() setLabel() press() release()
(e.g., it is common for an object to have methods that read or write values of its instance variables)
17

Example: Tetris
—What are the objects in this game?
Piece
Board
18

Example: Tetris
—What are their states and behaviors?
instance variables (state)
methods (behavior)
Board
level
score
pieces nextPieces
removeRow() levelUp() checkEndOfGame()
orientation position shape color
Piece
moveLeft() moveRight() rotate() fall()
19

Defining a Class in Java
—In Java, a class is defined using the keyword class
Dog
size breed name
makeNoise()
class Dog { int size;
String breed;
String name;
void makeNoise() { System.out.println(“Woof!”);
} }
20

Defining a Class in Java
—In Java, a class is defined using the keyword class
name of the class
defining a new class
Dog
size breed name
makeNoise()
class Dog { int size;
String breed;
String name;
void makeNoise() { System.out.println(“Woof!”);
} }
21

Defining a Class in Java
—In Java, a class is defined using the keyword class instance
Dog
size breed name
makeNoise()
class Dog { int size;
String breed;
String name;
void makeNoise() { System.out.println(“Woof!”);
} }
variables
a method
Woof!
22

A Tester Class
—A tester class is often used to test a new class
—Inside the main() method of a tester class
— Create objects of the new class using the new operator
— Access the instance variables and methods of the new objects using the dot operator
class DogTestDrive {
public static void main(String[] args) {
Dog d = new Dog(); // create a Dog object
d.size = 40; // set the size of the dog
d.makeNoise(); // call the makeNoise() method of the dog
} }
Not using
dot operator
Encapsulation!
23

Inheritance in Java
—In Java, a class (subclass) can be derived from an existing class (superclass) using the keyword
extends
overrides the makeNoise() method
superclass
Dog
size breed name
makeNoise()
class Poodle extends Dog { void makeNoise() {
System.out.println(“Ruff! Ruff!”); }
}
Poodle IS-A Dog, it will automatically inherit all the instance variables and methods of Dog
IS-A
P
P
e
o
o
o
o
d
dl
l
e
makeNoise()
subclass
24

—Example
Inheritance in Java
class PoodleTestDrive {
public static void main(String[] args) {
Dog d = new Poodle(); // create a Poodle object
d.size = 25; // set the size of the dog
d.makeNoise(); // call the makeNoise() method of the dog
} }
—Sample output Ruff! Ruff!
Polymorphism! Ruff! Ruff!
25

Challenge
—Suppose Poodle is modified as follows:
Points to remember
When using a superclass variable to hold a subclass object:
– Any method or variable
accessed must be in the
superclass.
– If the same method appears
in both superclass and subclass, the subclass version will be called.
You CANNOT use a subclass variable to hold a superclass object (e.g. Poodle d = new Dog() is wrong!).
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The method sing() is undefined for the type Dog
class Poodle extends Dog { void makeNoise() {
System.out.println(“Ruff! Ruff!”); }
void sing() { System.out.println(“Singing”);
} }
—What is the output of the following?
class PoodleTestDrive {
public static void main(String[] args) {
Dog d = new Poodle(); // create a Poodle object d.size = 25; // set the size of the dog
d.sing(); // call the sing() method of Poodle
} }
26

Example: A Guessing Game
—Summary
—The guessing game involves —1 ‘game’ object and
—2 ‘player’ objects
— The game generates a random number between 0 and 9 — The 2 players try to guess this number
— The game ends when either or both players make a correct guess, otherwise the game continues
27

Example: A Guessing Game
—Classes
— GameLauncher — GuessGame — Player
GameLauncher
main()
GuessGame
p1 p2
startGame()
Player
number name
guess()
28

Example: A Guessing Game
—GameLauncher class
—Used to launch the game
—main() method
—Create a GuessGame object
—Start the game by calling the startGame() method of the GuessGame object
makes a GuessGame object and calls its startGame() method
GameLauncher
main()
public class GameLauncher {
public static void main(String[] args) {
GuessGame g = new GuessGame();
g.startGame(); }
}
29

Example: A Guessing Game
— GuessGame class
—Instance variables for the 2
players —startGame() method
—Create 2 Player objects —Generate a random number —Ask each player to make a guess —Check the results
• Print out winning message; or
• Ask the players to make a guess again
instance variables for the 2 players
GuessGame
p1 p2
startGame()
game logic
30

Example: A Guessing Game
— GuessGame class
public class GuessGame { Player p1;
Player p2;
public void startGame() { p1 = new Player(); p1.name = “Player 1”; p2 = new Player(); p2.name = “Player 2”;
int targetNumber = (int) (Math.random() * 10); System.out.println(“Target number is ” + targetNumber);
31

Example: A Guessing Game
— GuessGame class
boolean isFinished = false; while (!isFinished) {
p1.guess();
p2.guess();
if (p1.number == targetNumber) {
System.out.println(p1.name + ” got it right!”);
isFinished = true; } // end if
if (p2.number == targetNumber) { System.out.println(p2.name + ” got it right!”); isFinished = true;
} // end if
} // end while
} // end startGame() }
32

Example: A Guessing Game
— Player class
— Instance variables for the guess
and the player’s name —guess() method
—Make a guess
—Print out the player’s name and his guess
instance variables for the guess and the player’s name
Player
number name
guess()
method for making a guess and printing out information
public class Player {
int number = 0; // where the guess goes
String name = “Player”; public void guess() {
number = (int) (Math.random() * 10);
System.out.println(name + ” guessed ” + number); }
}
33

Example: A Guessing Game
—Structure of the program
p1 (Player)
main()
g (GuessGame)
p2 (Player)
34

Example: A Guessing Game
— Sampleoutput
Target number is 8 Player 1 guessed 5 Player 2 guessed 4 Player 1 guessed 0 Player 2 guessed 4 Player 1 guessed 4 Player 2 guessed 6 Player 1 guessed 6 Player 2 guessed 1 Player 1 guessed 5 Player 2 guessed 4 Player 1 guessed 8 Player 2 guessed 3 Player 1 got it right!
35

main() Method
—A Java application is nothing but objects talking to
each other
—Start running by executing the main() method of the launching class
—In most Java application, the main() method does 2 and only 2 things
— Create an object
—Call a method of the object
36

main() Method
— The main() method does not return any value
— The name of the program is not included in the arguments (it is exactly the name of the class that contains the main() method!)
— The number of arguments needs not be included (an array in Java is an object who knows its own size!)
Java:
C++:
argument count
—Unlike C++
public static void main(String[] args)
int main(int argc, char* argv[])
argument vector (argv[0] contains the programname)
37

main() Method
—A Java application can accept any number of
arguments from the command line
—This allows the user to specify configuration information when an application is launched
public class Echo {
public static void main(String[] args) {
for (String arg : args) { System.out.println(arg);
} }
}
38

Garbage Collection
—Each time an object is created in Java, it goes into an area of memory known as the heap
—Java allocates memory space on the heap according to how much space that particular object needs (e.g., an object with 15 instance variables will probably need more space than an object with only 2 instance variables)
—Unlike C++,no need to explicitly free up memory using the delete operator
—Java manages the memory for you
39

Garbage Collection
—When an object can never be used again, it becomes eligible for garbage collection
—When the garbage is actually collected can be unpredictable
—When the system is running low on memory, the Garbage Collector will run, throw away those unreachable objects to free up the memory space
—The Java heap is therefore called the Garbage- Collectible Heap
40

We are with you!
If you encounter any problems in understanding the materials in the lectures, please feel free to contact me or my TAs. We are always with you!
We wish you enjoy learning Java in this class.
41

Chapter 2.
End
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
42