03 object-classes-pbl-4-slots

Click here to load reader

Upload: mha4

Post on 18-Feb-2017

69 views

Category:

Engineering


0 download

TRANSCRIPT

Titile

Lecture 03Chapter 6: Objects and Classes

(65 slides 4 slots)

Why should we study this lecture?This lecture willHelp you reviewing basic concepts of the object-oriented paradigm.Supply syntax for declaring a Java class. It can be a normal class, a sub-class, a nested class, abstract class or an interface. Supply ways to use Java classes.2

ReviewObject: i tng, nhng s vt, hin tng c th m con ngi s c cm xc v n. Th d ci xe my Air Blade c th m ta ang dngClass: lp, l mt tp cc i tng tng t nhau. Con ngi thng dng cc danh t chung (nh xe gn my) t tn gi cho mt class.Modifiers are Java keywords that give the compiler information about the nature of code (methods), data, classesAccess Modifiers: public, protected, private and no-modifier (default)Other modifiers: final, abstract, static, native, transient, synchronized, volatile3

ReviewType conversion = implicit type changeType casting = explicit type changeConversion allows widening type change only.If we want a narrowing type change, we must use an explicit casting.Object type conformity: fatherReferene=sonReference; 4

ReviewExceptions: Errors beyond the control of a program. When an exception occurs, the program will terminate abruptly.Exception can be caught by the try..catch..finally statementAssertions enables the programmer to test assumptions about the program. Assertions are introduced in Java 1.4. From Java 1.5, it is removed.Ways of writing assertion statements are:assert expression;assert expression1:expression2; Compiling a program having assertion statement: javac source 1.4 FileNameRunning a program with assertion java ea Package.FileClass java enableassertions Package.FileClass

5

ReviewKnowledge from the subject OOP: What are methods and constructors. Order of memory allocations, order of executions of constructors.

6

ObjectivesIntroduction to OO ParadigmBenefits of OO ImplementationHow to declare a classHow to use a classHow to declare a subclass

Your homework: Workshop 2 (with report)You are requested to complete the case stydy 1 introduced at the slide 22Assessment: the next class

7

Contents6.1- Introduction to OO Paradigm6.2- Benefits of OO Implementation6.3- Hints for class design6.4- Declaring/ Using a class6.5- Case study 1 (Managing a list of persons)6.6- Inheritance Demonstration6.7- Variable-length argument list6.8- Some Tests6.9- Nested Classes6.10- Interfaces6.11- Abstract Classes6.12- Anonymous Classes6.13- Enum TypesYou are introduced in the subject OOP

8

6.1- Introduction to OOPProcedure-Oriented Programdata1data2Function1 (data1)Function2 (data1)Function3 (data2)Function4 (data2)Class A{

}data1Function1 ()Function2 ()Class B{

}data2Function3 ()Function4()ModifiersModifiersObject = Data + MethodsBasic Concepts Encapsulation Inheritance PolymorphismParticular methods:ConstructorsConstructor: a specific method which is automatically called when an object is created.9

Introduction to OOPWhy OOP is introduced? It is a easy way to describe objects in nature.It supportsAbility to describe relationship between objects especially, the is a kind of relationship The problem is described easier and better InheritanceSecurity in code ModifiersAbility to maintain code EncapsulationPolymorphism overloading/overriding methods 10

6.2- Benefits of OO Impl.Encapsulation: Aggregation of data and behavior.Data of a class should be hidden from the outside. The outside access them by getters/settersAll behavior should be accessed only via methods.A method should have a boundary condition. The if statement is commonly used to ensure that this access is valid or data of the object are valid at any time.

class A{

}data1Function1 ()Function2 ()ModifiersBehavior: hnh vi, ability of an object which is identified and given a name (verb).Method: Phng thc, cch thc lm: Implementation of a behavior.11

Benefits of OO Impl.Inheritance: Ability allows a class having members of an existed class Re-used code.ID_NumnameyearOfBirthaddressgetID_Num()setID_Num(newID)......class PERSONrollNumscoregetScore()setSore(newScore)......class STUDENT

is a relationshipID_NumnameyearOfBirthaddressgetID_Num()setID_Num(newID)......class STUDENTrollNumscoregetScore()setSore(newScore)......inherited

extensions

Son = Father + extensions12

Benefits of OO Impl.How to implement Inheritance?Electric Products< code, name, make, price, guaranty, voltage, power>Ceramic Products < code, name, make, price, type >Food Products < code, name, make, price , date, expiredDate >

ProductcodenamemakepriceElectricProductguarantyvoltagepowerCeramictypeFooddateexpiredDate

The father class is implemented first then its subclasses afterwardsintersection rest 13

Benefits of OO Impl.Order of object creations:Memory block containing data inherited from Father is allocated first.Memory block containing extension data is allocated afterward.

GrandFather obj1 = new GrandFather();

Father obj1 = new Father();

Son obj2 = new Son();Data gfData fobj1: 1000obj2: 800obj3: 5001000800500Data sStep 1Step 2Data gfData fData gfStep 1Step 2Step 314

Benefits of OO ImplPolymorphism: Ability allows many versions of a method based on overloading and overriding methods techniques.

15

6.3- Hints for class designCoupling Is an objects reliance on knowledge of the internals of another entitys implementation.When object A is tightly coupled to object B, a programmer who wants to use or modify A is required to have an inappropriately extensive expertise in how to use B.Head

Eye1Eye2High coupling( Bad design)Head leftEye rightEye

EyeEyeLow coupling( Good design)16

Hints for class designCohesion is the degree to which a class or method resists being broken down into smaller pieces.classA M() {

}Operation 1Operation 2Low cohession( Bad design)classA M1() {

} M2() {

} M() { M1(); M2(); }Operation 1Operation 2High cohesion( Good design)17

6.4- Declaring/Using a Class[public] class ClassName [ extends FatherClass] { [modifier] DataType dataMember [=InitialValue]; [modifier] ClassName [(args)] // constructors { super (args); // call to the constructor of FatherClass first line } [ modifier] ReturnType methodName (args) { super.Method(args); // call to a method of FatherClass }}// Creating an objectClassName obj= new ClassName (args);obj.Method(args);Data of Objectobj: 1200012000Getters public Type getField()Setters public void setField(arg)WHY?What is the keyword super used?18

Key Points: Overloading MethodsA method that has an identical name and identical number, types, and order of arguments.Overloading methods are implemented in the same class.Overloading methods are the same name but their arguments have differences.19

Key points: Overriding methodsA method that has an identical name and identical number, types, and order of arguments as a method in a parent class is an overriding method.Each parent class method may be overridden once at most in any one subclass. An overriding method must return exactly the same type as the method it overrides.20

Overriding methodsAn overriding method must not be less accessible than the method it overrides. An overriding method must not throw any checked exception (or subclasses of those exceptions) that are not declared for the overridden method. An overridden method is completely replaced by the overriding method unless the overridden method is deliberately (c ) invoked from within the subclass.21

6.5- Case study 1To develop a program, steps must be followed:AnalysisDesignWriting ReportImplementTestGoals of this case study is providing a sample for writing a report including 2 first steps in your notebook for each problem you are requested to solve. 22

Report1- ProblemEach person details include code, name, and age.Write a Java program that allows users adding a new person to the list, removing a person having a known code from the list, updating details of a known-code person, listing all managed persons in descending order of ages using a simple menu. 23

Report1- Problem .2- AnalysisFrom the problem description. The following concepts will be implemented as appropriate classes:

Class PersonDescription for a personData: String code; String name; int ageMethods:ConstructorsGetters, settersvoid input() for collecting dataString toString() to get data in string format

24

ReportClass PersonListDescription for a list of personsData: Person[] list; // current listint count // current number of personsMethods:ConstructorsGetters, settersvoid add(); // add a new person. Data are collected from keyboardint find (String aCode); // Find the index of the person whose code is knownvoid remove()// remove a person. His/ her code is accepted from keyboardvoid sort(); // descending sort the list based on their agesvoid update(); // update a person, data are accepted from keyboardvoid print(); // print the list

25

ReportClass MenuDescription for a menuDataString[] hints; // list of hintsint n; // current number of hintsMethods:Menu(int n): constructor for initializing a menu containing n optionsvoid add (String aHint); // add an optionint getChoice(); // get an option

Class ManagingProgram1Description for the programData: noneMethods:main(): main method of the program

26

Report

Program structure

AlgorithmsPlease seeing comments in codes.

3- Implementation and ResultPlease check the program.

End of report27

Case study 1: Design Guide

28

this: reference of the current objectCase study 1: Implementation29

Case study 1: Implementation

30

Case study 1: Implementation

31

Case study 1: Implementation

32

Case study 1: Implementation

33

Case study 1: Implementation

34

Case study 1: Implementation

35

6.6- Inheritance Demonstration

36

Studying Subclass Implementation

37

6.7- Variable-length argument Lists

38

6.8- Some Tests

a) ABCb) AACc) ABAd) Compile-time errorStudy_1A and Study_1C are inconvertible39

Some Testsa) ABCb) AACc) ABAd) Compile-time errorThe java.lang.Object class does not have the M() method

40

Some Tests

a) ABCb) AAAc) ABAd) None of the othersAB and a ClassCastException41

Some Tests

a) AAAb) ACBc) None of the othersd) ABC42

Some Test

a) ABCb) AAAc) ABAd) None of the othersCompile-time error( Type conformity violation)43

Some Testa) 120b) 120Ac) None of the othersd) A120

44

Some Testsa) A7500b) 500A7c) 500d) None of the othersCompile-time error( static code can not access instance variables)

45

Some Tests

a) A1210b) 10A12c) 17d) None of the othersCompile-time error( The y variable is out of scope)46

A summaryIntroduction to OO ParadigmBenefits of OO ImplementationHints for class designDeclaring/ Using a classIdentifying a class:Main noun ClassDescriptive nouns Data/ constantsVerbs Behaviors MethodsImplementing a classConstructorsMethodsGetters, settersMethods accepting variable-length argument list47

6.9- Inner-Nested classes Class is declared inside some other class or inside the body of other classs method. 2 types of nested class: Static Nested classes, Inner classes ( non-static)Static nested class All objects belong to the outer class share one nested object(cp song sinh dnh nhau, phn dnh nhau nm bn ngoi).Inner class: Each outer object has its own inner object Outer object must contain an instance of the inner object then accesses members of this nested instance (tri tim nm bn trong thn ngi)obj1obj2Static nested objobj1

Inner objobj2

Inner obj48

Inner-Nested classesA nested class violates the recommendation low coupling in class design. Why are nested classes used?It is a way of logically grouping classes that are only used in one place. It increases encapsulation. Nested classes can lead to more readable and maintainable code. 49

Static Nested Classes DemoClass-level nested class.Because the static nested object is stored separately from enclosing instances, static nested object can be initiated without enclosing objects.

Methods of static nested class can not access data of enclosing instance because it can created even when enclosing objects do not exist.50

Inner classes demoobj

obj: 2000x = 5inner: 3000y = 7

A method of nested class can access all members of its enclosing class outerObjx=5

innerObjy=7Error: inner obj do not created yet.2000300051

Creating Inner Class instance through enclosing instanceobj: 1000x = 5in1: 2000y = 1

in2: 3000z = 2

200030001000

52

Inner Classes Defined Inside Methods

Local classInner-method class can not access normal local variables of the containing method. 53

6.10- Abstract classesThe result of so-high generalization.Use the keyword abstract to declare an abstract class or an abstract method.Abstract method is a prototype (no body).An instance of abstract class can not be created but concrete objects (all abstract methods were implemented).

Modified54

Abstract classes

This class have no abstract method but it is declared as an abstract class. So, we can not initiate an object of this class.55

Abstract classes

Error. Why?56

6.11- Interfaces

Interface: A group of methods prototypes which will be implemented in a concrete class.You can not create an instance of an interface.Access modifier of a method of an interface can be default but it must be public in a class implementing this interface.Modified.57class A implements Iterafce_1, Interface_2{ .}

InterfacesWhen is an interface designed? When methods must be implemented in some classes.Advantages of interfaces:A way to make a model (template) for a kind of applications.A way for designer controlling implementers.58

6.12- Anonymous ClassWe can initiate concrete objects only (all methods were implemented and they are not abstract ones).Java permits we create directly an object of an interface or an abstract class if all prototypes and abstract methods are implemented. We can not develop a class which implements this interface or extends the abstract class. We can not a chance to give a class name to these code Anonymous class.When the program is compiled, the class name will be given by the compiler. 59

Anonymous Class

Anonymous class.Class name is given by the compiler:ContainerClass$Number60

Anonymous Class

Anonymous class is a technique is commonly used to support programmer when only some methods are overridden only especially in event programming.Concrete methods but they can not be used because the class is declared as abstract one.The abstract class can be used only when at least one of its methods is overridden61

6.13: Enum TypeIt is introduced from Java 1.5.An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because they are constants, the names of an enum type's fields are in uppercase letters.Similarities between traditional classes and enums: refer to the page 198. Enum type is a group of constants. It is given a name. Each constant is given a name (name of constant).

62

Enum Types Demo

63

Summary6.1- Introduction to OO Paradigm6.2- Benefits of OO Implementation6.3- Hints for class design6.4- Declaring/ Using a class6.5- Case study 1 (Managing a list of persons)6.6- Inheritance Demonstration6.7- Variable-length argument list6.8- Some Tests6.9- Nested Classes6.10- Interfaces6.11- Abstract Classes6.12- Anonymous Classes6.13- Enum Types64

Thank You

65