CS计算机代考程序代写 Java c/c++ data structure jvm ER compiler Chapter 1.

Chapter 1.
Introduction
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

Procedural Programming
— Emphasisisontaskstobedone
— Breakdownaproblemintoanumberoftasksand
sub-tasks (top-down design approach)
— Implementtasksandsub-tasksasfunctions
— Afunctionissimplyagroupofinstructionsthatare executed when the function is being called
— Aprogramiscomposedofacollectionoffunctions that operate on some (shared) data
2

Procedural Programming
— Typical structure of a program in procedural programming
main program
function 1
function 2
function 3
function 4
function 5
function 6
function 7
function 8
3

Procedural Programming
— Datamaybeaccessedbymultiplefunctionsand become vulnerable (hard to trace when something goes wrong!)
— Difficulttomaintainandextend(e.g.,changinga data structure involves modifying all functions that work with that data structure)
— Code reusability is low
4

Object-Oriented Programming
— Emphasis is on data
— Decompose a problem into a number of entities
called objects (bottom-up design approach)
— Implementobjectsusingclasses
— A class is like a blueprint for an object, it defines the state (data) and behavior (operations) supported by an object
— Aprogramiscomposedofacollectionofobjects which interact with each other
5

Object-Oriented Programming
— Typical structure of a program in object-oriented programming
Object A data
operations
Object B data operations
Object C data
operations
6

Object-Oriented Programming
— Dataofanobjectcanbeaccessedonlybyoperations associated with that object (protected from external access, easy to trace)
— Operationsofanobjectcan,however,accessthe operations of other objects (object interaction)
— Easytomaintainandextend(e.g.,changingadata structure inside a class involves only modifying operations of that class which work with that data structure)
— Codereusabilityishigh(throughreusingexistingclasses or deriving new classes from existing classes)
7

Objects in OOP
— Anobjecthasbothstate(data)andbehavior(operations)
— Dataofanobjectarestoredinitsinstancevariables
— Operationsthatanobjectcanperformarecalledits methods
— Objectscanbeusedtomodelrealworldobjects(e.g., car, dog), as well as concepts (e.g., date, bank account)
— Anobjectinstantiated(created)fromaclassiscalledan instance of that class
8

Objects in OOP
— Instancesofthesameclass
— Havethesamesetofinstancevariables that represent their states (e.g., balance of a bank account)
— Theactualvaluesstoredintheirinstance variables may be different
a class
BankAccount
balance
withdraw() deposit() checkBalance()
— Havethesamesetofmethods(e.g.,withdrawingmoney from a bank account, depositing money into a bank account, checking the balance of a bank account)
— Theiractualbehaviors,however,dependontheirownstates (e.g., withdrawing money from a bank account with a non- positive balance may not be successful)
9

Fundamental OOP Concepts
— Abstraction
— Theactofrepresentingessentialfeatureswithoutincluding
background details
— Encapsulation
— Theactofwrappingupofdataandoperationsintoasingle
unit
— Inheritance
— Theprocessbywhichobjectsofoneclassacquirethe
properties of objects of another class
— Polymorphism
— Theabilitytotakemorethanoneform
10

Abstraction
— Theactofrepresentingessentialfeatureswithoutincluding background details
— Focusonwhatanobjectisordoesratherthanhowitis represented or how it works
— Provideanabstractdescriptionofanobjectbytakingaway unimportant details (problem dependent!)
— Modelonlynecessaryandcommonproperties of objects (e.g., all types of bank accounts maintain a balance, and support methods like withdrawing money, depositing money and checking balance)
— Essentialinthedesignofclassesandobjects
BankAccount
balance
withdraw() deposit() checkBalance()
11

Encapsulation
— Theactofwrappingupofdataandoperationsintoa single unit (i.e., an object)
— Hidetheactualimplementations(ofbothdataand operations) from the outside world
— Datacannotbeaccesseddirectlyfromoutsideanobject (information hiding)
— Interactionswithanobjectonlythroughitsexposed interface (public methods)
— Allowchanginginternalimplementationsofanobject without hurting the overall functioning of the system
— Essentialintheimplementationofclassesandobjects
12

A Real World Example
— Abstraction and encapsulation
The actual implementations (e.g., circuit logic and electronic components) are hidden inside the case
Television
listOfChannels currentChannel currentVolume onOffState
channelUp() channelDown() volumeUp() volumeDown() switchOn() switchOff()
13

Inheritance
— Theprocessbywhichobjectsofoneclass acquire the properties of objects of another class
— OOPallowsanewclasstobederivedfrom an existing class
— Thenewclassisknownasasubclassofthe existing class from which it is derived, and the existing class is referred to as the superclass of the derived class
— Asubclasswillautomaticallyinheritallthe properties (both instance variables and methods) of its superclass
subclass
superclass
food
hunger location
Animal
makeNoise() eat()
sleep() roam()
Cat
14

Inheritance more abstract
— ThereexistsaIS-Arelationshipbetweena subclass and its superclass (e.g., if Cat class is a subclass of Animal class, then Cat IS- A(n) Animal)
— Asubclasscanoverridemethodsofits superclass by providing its own implementations of the methods
— Asubclasscanalsointroducenewinstance variables as well as new methods
IS-A(n)
food
hunger location
Animal
makeNoise() eat()
sleep() roam()
C
a
Ca
t
t
t
breed
makkeeNNoisoei(s)e() eat()
play()
— Asubclasscanbeconsideredasa specialization of its superclass
more specific
15

Inheritance
— Support the concept of hierarchical classification an inheritance tree
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
Dog
makeNoise() eat()
Cat
breed
makeNoise() eat()
play()
Tiger
makeNoise() eat()
Poodle
makeNoise() eat()
play()
16

Polymorphism
— The ability to take more than one form
— OOP allows a subclass object be used in place of its superclassobject(IS-Arelationship!)
— Examples
— AmethodtakinganAnimalobjectasitsargumentcan also take a Cat object as its argument given Cat class is a subclass of Animal class (Cat IS-A(n) Animal!)
— AnarraydeclaredtoholdAnimalobjectscanalsoholda Cat object or a Dog object given both Cat class and Dog class are subclasses of Animal class
17

Polymorphism
— Considerobjectsinstantiatedfromdifferentsubclasses (e.g., Cat class & Dog class) of a common superclass (e.g.,Animal class)
— Theyallhaveidenticallynamedmethods(overriddenor not) inherited from their common superclass (e.g.,
makeNoise(), eat())
— Makingacalltothesamemethod(e.g.,makeNoise())of these objects will result in different behaviors depending on the actual subclass object being called
Woof!
Meow!
18

Polymorphism
— Supportdesigningmethodsthat can work with objects instantiated from a class as well as from all of its subclasses (including any future subclasses!)
a possible future subclass
makeNoise() eat()
play()
Animal
food
hunger location
makeNoise() eat()
sleep() roam()
Dog
makeNoise() eat()
Cat
breed
makeNoise() eat()
play()
Tig er
makeNoise() eat()
Poodle
???
19

Java
— Aprogramminglanguagethatis
— Simple–Javaisdesignedtobeeasytolearn.Syntax is similar to C/C++, with some features (e.g., structure, pointer) removed
— Object-oriented–InJava,everythingisanobject
— Platformindependent–AJavaprogramiscompiled into platform independent byte code that can be executed by virtual machines on different platforms
— Architectural-neutral –Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors
20

Java
— Aprogramminglanguagethatis(continue…)
— Portable –Being architectural-neutral and having no implementation dependent aspects of the specification make Java portable
— Robust–Withcompiletimeerrorcheckingand runtime error checking
— Multi-threaded–itispossibletowriteprogramsthat can do many tasks simultaneously
— Highperformance,secure,distributed,dynamic…
21

Write Once, Run Anywhere
— StepstoproduceandrunaJavaprogram
22

Code Structure in Java
— Putaclassinasourcefile
A source code (*.java) holds one class definition. The class represents a piece of your program. The body of the class must go within a pair of curly braces.
public class Example { void method1() {
statement1;
statement2; }
void method2() { statement3; statement4; statement5;
} }
Example.java
23

Code Structure in Java
— Put methods in a class
public class Example { void method1() {
statement1;
statement2; }
void method2() { statement3; statement4; statement5;
} }
A class has one or more methods. All methods must be declared inside a class
Example.java
24

Code Structure in Java
— Putstatementsinamethod
public class Example { void method1() {
statement1;
statement2; }
void method2() { statement3; statement4; statement5;
} }
A method holds statements (instructions) for how that particular method should be performed
Example.java
25

My First Java Program
public class MyFirstApp {
public static void main(String[] args) {
System.out.println(“This is my first app”);
System.out.println(“Hello World”); }
}
— EveryJavaapplicationhastohaveatleastoneclass
— ThemainJavaclass(thatistheclassyoucallusing “java”) has to have one main() method
26

this is a class
My First Java Program
name of the class
public class MyFirstApp {
public static void main(String[] args) {
System.out.println(“This is my first app”);
System.out.println(“Hello World”); }
}
publicly accessible
the body of the class is enclosed within a pair of curly braces
27

return type of the method
name of the method
arguments to the method
My First Java Program
public class MyFirstApp {
public static void main(String[] args) {
System.out.println(“This is my first app”);
System.out.println(“Hello World”); }
}
the body of the method is enclosed within a pair of curly braces
28

My First Java Program
public class MyFirstApp {
public static void main(String[] args) {
System.out.println(“This is my first app”);
System.out.println(“Hello World”); }
}
statements in the method
this statement simply prints its argument to the standard output
each statement ends with a semi-colon ;
string to be printed
29

My First Java Program
public class MyFirstApp {
public static void main(String[] args) {
System.out.println(“This is my first app”);
System.out.println(“Hello World”); }
}
1. Type the source code and save it as MyFirstApp.java 2. Compile it into MyFirstApp.class
3. Run the program under Java Virtual Machine (JVM)
30

My First Java Program
public class MyFirstApp {
public static void main(String[] args) {
System.out.println(“This is my first app”);
System.out.println(“Hello World”); }
}
— WhentheJavaVirtualMachine(JVM)startsrunning, it will first load the MyFirstApp class
— Next the JVM will look for the main() method of the MyFirstApp class and start executing it
31

Statements in a Method
— Declarations,assignments,methodcalls,etc.
int x = 3;
String name = “OOP”;
x = x * 17; System.out.print(“x is ” + x); double d = Math.random();
— Branching
if (x == 10) {
System.out.print(“x must be 10”);
} else {
System.out.print(“x isn’t 10”);
}
32

Statements in a Method
— Loops
int x = 0;
while (x < 10) { System.out.println("x is now " + x); x = x + 1; } for (int x = 0; x < 10; x = x + 1) { System.out.println("x is now " + x); } — Commentlines // this is a comment line /* this is a comment spanning multiple lines */ 33 Boolean Test in Java — Notethatabooleanandanintegerarenot compatible types in Java — Hence the following boolean test is illegal in Java — Theonlyvariablethatcanbedirectlytested(without using a comparison operator) is a boolean int x = 1; while (x) { ... } boolean isHot = true; while (isHot) { ... } 34 Example: Phrase-O-Matic — Whatdoesthefollowingapplicationdo? public class PhraseOMatic { public static void main(String[] args) { String[] girls = {"Amanda", "Jessica", "Chrissie"}; String[] verbs = {"loves", "hates"}; String[] boys = {"Andy", "Aaron", "Eason", "Jacky"}; int i = (int) (Math.random() * girls.length); int j = (int) (Math.random() * verbs.length); int k = (int) (Math.random() * boys.length); System.out.print(girls[i] + " " + verbs[j] + " " + boys[k]); } } 35 Example: Phrase-O-Matic — Whatdoesthefollowingapplicationdo? public class PhraseOMatic2 { public static void main(String[] args) { String[] girls = {"Amanda", "Jessica", "Chrissie"}; String[] verbs = {"loves", "hates"}; String[] boys = {"Andy", "Aaron", "Eason", "Jacky"}; for (int i = 0; i < girls.length; i++) { int j = (int) (Math.random() * verbs.length); int k = (int) (Math.random() * boys.length); System.out.println(girls[i] + " " + verbs[j] + " " + boys[k]); } } } 36 Example: Phrase-O-Matic — Whatdoesthefollowingapplicationdo? public class PhraseOMatic3 { public static void main(String[] args) { String[] girls = {"Amanda", "Jessica", "Chrissie"}; String[] verbs = {"loves", "hates"}; String[] boys = {"Andy", "Aaron", "Eason", "Jacky"}; for (String girl : girls) { // for each string in girls[] int j = (int) (Math.random() * verbs.length); int k = (int) (Math.random() * boys.length); System.out.println(girl + " " + verbs[j] + " " + boys[k]); } } } 37 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. 38 Chapter 1. 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 39