21
10/11/18 1 A.Prof. Tran Van Lang, PhD Vietnam Academy of Science and Technology (VAST) A.Prof. Tran Van Lang, PhD. § Lesson 8: Object-Oriented Programming ( http://www.oracle.com/technetwork/java/oo- 140949.html#what ) § Java Programming Tutorial: Object-oriented Programming (OOP) Basics ( https://www3.ntu.edu.sg/home/ehchua/programming/java/ J3a_OOPBasics.html ) § Java Tutorial (https://www.tutorialspoint.com/java/ ) A.Prof. Tran Van Lang, PhD. § Object-Oriented Programming (OOP) in Java § Members § Constructors § Other Properties § Fundamental OOP Concepts A.Prof. Tran Van Lang, PhD. § Object-Oriented Programmning Defined § Classes and Object § Class Definition in Java A.Prof. Tran Van Lang, PhD.

[email protected]/~lang/lecture/java/[email protected] · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

1

A.Prof. Tran Van Lang, PhD

Vietnam Academy of Science and Technology (VAST)

A.Prof. Tran Van Lang, PhD.

§Lesson 8: Object-Oriented Programming (http://www.oracle.com/technetwork/java/oo-140949.html#what)

§ Java Programming Tutorial: Object-oriented Programming (OOP) Basics (https://www3.ntu.edu.sg/home/ehchua/programming/java/J3a_OOPBasics.html)

§ Java Tutorial (https://www.tutorialspoint.com/java/)

A.Prof. Tran Van Lang, PhD.

§Object-Oriented Programming (OOP) in Java§Members

§Constructors§Other Properties

§Fundamental OOP Concepts

A.Prof. Tran Van Lang, PhD.

§Object-Oriented Programmning Defined§Classes and Object

§Class Definition in Java

A.Prof. Tran Van Lang, PhD.

Page 2: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

2

§Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined and cooperating objects.

§Traditional procedural-oriented programming languages suffer some notable drawbacks in creating reusable software components as follows:§ The procedural-oriented programs are made up of functions.

Functions are less reusable. § It is very difficult to copy a function from one program and reuse in another

program because the function is likely to reference the global variables and other functions.

A.Prof. Tran Van Lang, PhD.

§ The procedural languages are not suitable of high-level abstraction for solving real life problems.

§ The traditional procedural-languages separate clearly the data structures (variables) and algorithms (functions)

A.Prof. Tran Van Lang, PhD.

§Object-oriented programming (OOP) languages are designed to overcome these problems.§ The basic unit of OOP is a class, which encapsulates both the static

properties and dynamic operations within a "box", and specifies the public interface for using these boxes. Since classes are well-encapsulated, it is easier to reuse these classes. § In other words, OOP combines the data structures and algorithms of a software

entity inside the same box.

A.Prof. Tran Van Lang, PhD.

§ OOP languages permit higher level of abstraction for solving real-life problems. § The traditional procedural language (such as C and Pascal) forces you to think in

terms of the structure of the computer (e.g. memory bits and bytes, array, decision, loop) rather than thinking in terms of the problem you are trying to solve.

§ The OOP languages (such as Java, C++ and C#) let you think in the problem space, and use software objects to represent and abstract entities of the problem space to solve the problem.

A.Prof. Tran Van Lang, PhD.

Page 3: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

3

§For example, suppose you wish to write a computer soccer games. In OOP languages, we can easily model the program accordingly to the "real things" appear in the soccer games.§ Player§ Ball:§ Field:§ Audience:

§Most importantly, some of these classes (such as Ball and Audience) can be reused in another application, e.g., computer basketball game, with little or no modification.A.Prof. Tran Van Lang, PhD.

§A class is a structure data type that defines the data and the methods to work on that data.

§When we write programs in the Java language, all program data is wrapped in a class, whether it is a class we write or a class we use from the Java platform API libraries.

§The classes (in the previous section) are examples§An instance is an executable copy of a class. Another name

for instance is object. There can be any number of objects of a given class in memory at any one time.

A.Prof. Tran Van Lang, PhD.

§A class is a definition of objects of the same kind. § In other words, a class is a blueprint, template, or prototype that

defines and describes the static attributes and dynamic behaviors common to all objects of the same kind.

§A object is a realization of a particular item of a class. § In other words, a object is an instantiation of a class. All the instances

of a class have similar properties, as described in the class definition. § For example, you can define a class called "Girl" and create three instances of the

class "Mai" for "Lan", "Cuc" and "Truc".

A.Prof. Tran Van Lang, PhD. A.Prof. Tran Van Lang, PhD.

Lan Cúc TrúcMai

girlclassobject

Page 4: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

4

§A Class is a 3-Compartment Box Encapsulating Data and Operations:§ Name (or identity): identifies the class§ Variables (or attribute, state, field): contains

the static attributes of the class§ Methods (or behaviors, function, operation):

contains the dynamic behaviors of the class

A.Prof. Tran Van Lang, PhD.

§For example, Student class, Car class:

A.Prof. Tran Van Lang, PhD.

§ In Java, we use the keyword class to define a class. For examples:class Student{ // Name

String name; // Variablesfloat gpa;

String getName() { // Methods

//... }

void setGPA() {//...

}}

A.Prof. Tran Van Lang, PhD.

§To create an instance (object) of a class, we have to:§Declare an instance identifier (instance name) of a particular class.§Construct the instance (i.e., allocate storage for the instance and

initialize the instance) using the new operator.

§For example, with Girl classGirl g1, g2, g3, g4;g1 = new Girl( "Mai" )g2 = new Girl( "Lan" )g3 = new Girl( "Cuc" )g4 = new Girl( "Truc" )

A.Prof. Tran Van Lang, PhD.

Page 5: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

5

§Member Variables and Methods§Dot (.) Operator

§Examples

A.Prof. Tran Van Lang, PhD.

§The variables and methods belonging to a class are formally called member variables (or fields) and member methods.

§To reference a member variable or method, we must:§ First identify the instance you are interested in, and then,§ Use the dot operator (.) to reference the desired member variable or

method.

§For example, with Student class

A.Prof. Tran Van Lang, PhD.

§So that we have a name class called Student, with two member variables (name and gpa) and two member methods (getName(), getGPA() and setGPA()).

§We have created three instances of the class Student, namely, s1, s2 and s3.

§To invoke the method setGPA(), we must first identity the instance of interest, says s2, then use the dot operator, in the form of s2.setGPA()

A.Prof. Tran Van Lang, PhD.

§Some illustration statements:Student s1, s2, s3; // Create 3 objectss1.gpa = 9s2.gpa = 7

// Display GPA of s2 StudentSystem.out.println("GPA of St. " + s2.getName() + " is " + s2.getGPA())

Dot operator

A.Prof. Tran Van Lang, PhD.

Page 6: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

6

§Modify the Birthday2Age examples of previous section with following members to become Birthday2AgeClass :public class BirthYear2AgeClass {

String name;int birthday;void todo() { ... }void getData() { ... }void display() { ... }public static void main( String[] args ) { ... }

}

A.Prof. Tran Van Lang, PhD.

§The Birthday2AgeClass program

A.Prof. Tran Van Lang, PhD.

§Member Methods

A.Prof. Tran Van Lang, PhD.

§General Concept§Constructor Method in Java

§Destructor

A.Prof. Tran Van Lang, PhD.

Page 7: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

7

§A constructor method looks like a special method that has the same method name as the class name.

§A constructor is used to construct and initialize all the member variables

§This method has been invoked when an instance was created.

A.Prof. Tran Van Lang, PhD.

§A constructor is different from an ordinary method in the following aspects:§ In Java, the name of the constructor method is the same as the class

name. § Constructor has no return type. No return statement is allowed inside

the constructor's body.§ Constructor can only be invoked via the "new" operator. We cannot

call the constructor anymore.§ Constructors are not inherited

A.Prof. Tran Van Lang, PhD.

§A constructor with no parameter is called the default constructor.

§ It initializes the member variables to their default value. For example, § Modify the Birthday2AgeClass class in the above example to invoke

init() and getDate() method.

A.Prof. Tran Van Lang, PhD.

§The Birthday2AgeClass2 program

A.Prof. Tran Van Lang, PhD.

Page 8: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

8

§and the Constructor:

A.Prof. Tran Van Lang, PhD.

§The finalize() method is a destructor of Java. protected void finalize(){

//...}

§When the job of an object is over - the object is no more used in the program, the object is known as garbage.

§The process of removing the object from a running program is known as garbage collection.

A.Prof. Tran Van Lang, PhD.

§Garbage collection frees the memory and this memory can be used by other programs or the same program further in its execution.

§Before an object is garbage collected, the JRE (Java Runtime Environment) calls the finalize() method.

§The finalize() method can be best utilized by the programmer to close the file, socket handles, ...

A.Prof. Tran Van Lang, PhD.

§Method Overloading§The public vs. private - Access Control Modifiers

§Keyword "this"

A.Prof. Tran Van Lang, PhD.

Page 9: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

9

§Method overloading means that the same method name can have different implementations.

§However, the different implementations must be distinguishable by their parameter list (either the number of parameters, or the type of parameters, or their order)

§So, in a class there can be many constructors

A.Prof. Tran Van Lang, PhD.

§An access control modifier can be used to control the visibility of a class, or a member variable or a member method within a class.

§We begin with the following two access control modifiers:§ public: The class/variable/method is accessible and available

to all the other objects in the system.§ private: The class/variable/method is accessible and

available within this class only.

A.Prof. Tran Van Lang, PhD.

§We can use keyword "this" to refer to this instance inside a class definition.

§One of the main usage of keyword this is to resolve ambiguity. For example:public class Circle {

double radius; // Member variable called "radius" public Circle( double radius ) {

this.radius = radius; } ...

}A.Prof. Tran Van Lang, PhD.

§There are 2 classes: Car and TestCar Class.

§They are stored in 2 files: Car.java and TestCar.java

A.Prof. Tran Van Lang, PhD.

Page 10: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

10

§TestCar has-a Car. This is a relationship HAS-A

A.Prof. Tran Van Lang, PhD.

§The following classes to convert date into different kinds:

A.Prof. Tran Van Lang, PhD.

§ Into the Days of week

A.Prof. Tran Van Lang, PhD.

§and the US Date class

A.Prof. Tran Van Lang, PhD.

Page 11: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

11

§This is TestDate class.

§Using Has-a Relationship to create TestDate class

A.Prof. Tran Van Lang, PhD.

§ Inheritance§Abstraction - Interface

§Polymorphism§Encapsulation – Data Hiding

A.Prof. Tran Van Lang, PhD.

§One object-oriented concept that helps objects work together is inheritance.

§ Inheritance defines relationships among classes in an object-oriented language.

§ In the Java programming language, all library classes descend from java.lang.Object and implement its methods.

§The following diagram shows the class hierarchy as it descends from java.lang.Object for the classes

A.Prof. Tran Van Lang, PhD. A.Prof. Tran Van Lang, PhD.

Page 12: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

12

§ Inheritance can be defined as the process where one class acquires the properties (methods and variables - fields) of another.

§With the use of inheritance the information is made manageable in a hierarchical order.

§The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

A.Prof. Tran Van Lang, PhD.

§extends is the keyword used to inherit the properties of a class.

§Following is the syntax of extends keyword.class SuperClass {

//.....} class SubClass extends SuperClass {

//..... }

A.Prof. Tran Van Lang, PhD.

§Following is an example demonstrating Java inheritance. § In this example, we can observe two classes namely Car and

CarDetail.§Using extends keyword, the CarDetail inherits the methods

getPlateNumber() and getAutomaker() of Car class.§There is a way of saying: CarDetail is-a Car. This is an IS-A

Relationship.

A.Prof. Tran Van Lang, PhD.

§The CarDetailClass.

§To invoke constructor of parent Class, using super()method

A.Prof. Tran Van Lang, PhD.

Page 13: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

13

§TestCarDetail Class

A.Prof. Tran Van Lang, PhD.

§ super is also the keyword used to invoke a member of super class when these members name are the same. For example

class Animal {public void move() {

System.out.println( "Animals can move" );}

}class Dog extends Animal {

public void move() {super.move(); // invokes the super class methodSystem.out.println( "Dogs can walk and run" );

}}

A.Prof. Tran Van Lang, PhD.

§An abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user.

§ In other words, the user will have the information on what the object does instead of how it does it.

§ In Java, abstraction is achieved using Abstract classes and Interface.

A.Prof. Tran Van Lang, PhD.

§A class which contains the abstract keyword in its declaration is known as abstract class.§ Abstract classes may or may not contain abstract methods, i.e.,

methods without body ( public void get(); )§ But, if a class has at least one abstract method, then the class must be

declared abstract.§ If a class is declared abstract, it cannot be instantiated.§ To use an abstract class, we have to inherit it from another class,

provide implementations to the abstract methods in it.§ If you inherit an abstract class, we have to provide implementations to

all the abstract methods in it.A.Prof. Tran Van Lang, PhD.

Page 14: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

14

§Abstract method is a method declared in the parent class, but the actual implementation of that method to be determined by child classes.§ abstract keyword is used to declare the method as abstract.§ We have to place the abstract keyword before the method name in

the method declaration.§ An abstract method contains a method signature, but no method

body.§ Instead of curly braces, an abstract method will have a semoi colon (;)

at the end.

A.Prof. Tran Van Lang, PhD.

§ In Java, to create an abstract class, just use the abstract keyword before the class keyword, in the class declaration. For Example,public abstract class Machine {

private String name;private String kind;public Machine( String n, String k){}String getName(){}String getKind(){}

}

A.Prof. Tran Van Lang, PhD.

§ We can implement an abstract class is same as normal class in Java; it still has 2 fields, 2 methods, and 1 constructor.

§ But we can not instantiatethe Machine class.

§To instantiate, we have to inherit the properties of Machine class just like concrete class, for example:public class Computer extends Machine {

private String cpuKind;public Computer( String cpu ){

supper( String name, String kind );//...

}String getCPU(){ ... }

}

A.Prof. Tran Van Lang, PhD.

§We can declare an abstract class by using abstract methodas follow:public abstract class Pupil {

private float grade[9];private float gpapublic Student( float g[] ){

//...}void getGPA();

}

A.Prof. Tran Van Lang, PhD.

Page 15: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

15

§ In the inheritent class, we have to implement this abstract methodpublic class Student extends Pupil {

//...void getGPA() {

gpa = 0.0f;for ( int i = 0; i < 9; i++ )

gpa += grade[i]; //sum of grade of 9 subjectsgpa /= 9;

}}

A.Prof. Tran Van Lang, PhD.

§An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.

§A class implements an interface, thereby inheriting the abstract methods of the interface.

§Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

A.Prof. Tran Van Lang, PhD.

§Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

§Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

A.Prof. Tran Van Lang, PhD.

§An interface is similar to a class in the following ways −§ An interface can contain any number of methods.§ An interface is written in a file with a .java extension, with the name

of the interface matching the name of the file.§ The byte code of an interface appears in a .class file.

A.Prof. Tran Van Lang, PhD.

Page 16: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

16

§However, an interface is different from a class in several ways, including:§ You cannot instantiate an interface.§ An interface does not contain any constructors.§ All of the methods in an interface are abstract.§ An interface cannot contain instance fields. The only fields that can

appear in an interface must be declared both static and final.§ An interface is not extended by a class; it is implemented by a class.§ An interface can extend multiple interfaces.

A.Prof. Tran Van Lang, PhD.

§The interface keyword is used to declare an interface. Here is a simple example to declare an interface.public interface Position {

float getXLocation();float getYLocation();

}public interface Speed {

float getSpeed();}

A.Prof. Tran Van Lang, PhD.

public interface MovedObject extends Position, Speed {

void setData( float x, float y, float s );}

§We can use interfaces in Java as a way to achieve polymorphism.

§ Java does not allow multiple inheritance, so Interface is a solution

A.Prof. Tran Van Lang, PhD.

§Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

§Any Java object that can pass more than one IS-A test is considered to be polymorphic.

§ In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

A.Prof. Tran Van Lang, PhD.

Page 17: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

17

§ It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

§The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A.Prof. Tran Van Lang, PhD.

§A reference variable can refer to any object of its declared type or any subtype of its declared type.

§A reference variable can be declared as a class or interface type.

§For examplepublic interface Lecturer {}public class Student {}public class PhDStudent extends Student implements Lecture{}

A.Prof. Tran Van Lang, PhD.

A.Prof. Tran Van Lang, PhD.

Page 18: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

18

§Classes of this heritage as follows:§ Student Class (Student.java)§ Lecture Interface

(Lecture.java)§ PhDStudent Class

(PhDStudent.java)

A.Prof. Tran Van Lang, PhD.

Page 19: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

19

A.Prof. Tran Van Lang, PhD. A.Prof. Tran Van Lang, PhD.

§Now, the PhDStudent class is considered to be polymorphic since this has multiple inheritance.

§Following are true for the above examples:

§ A PhDStudent IS-A Student§ A PhDStudent IS-A Lecturer§ A PhDStudent IS-A PhDStudent§ A PhDStudent IS-A Object

A.Prof. Tran Van Lang, PhD.

§When we apply the reference variable facts to a PhDStudent object reference, the following declarations are legal:

PhDStudent p = new PhDStudent();Student s = p;Lecturer l = p;Object o = p;

A.Prof. Tran Van Lang, PhD.

Page 20: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

20

§Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

§Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit.

§ In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

A.Prof. Tran Van Lang, PhD.

§To achieve encapsulation in Java:§ Declare the variables of a class as private.§ Provide public setter and getter methods to modify and view the

variables values.

§For examplepublic class Person {

private String name;private int birthyear;String getName() {

return name; }

A.Prof. Tran Van Lang, PhD.

int getBirthyear() { return birthyear;

} void setName( String name ) {

this.name = name; } void setBirthyear( int birthyear ) {

this.birthyear = birthyear; }

}

A.Prof. Tran Van Lang, PhD.

§The setXXX() and getXXX() methods are the access points of the instance variables of the Person class.

§Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters.

§The variables of the Person class can be accessed using the following program:

A.Prof. Tran Van Lang, PhD.

Page 21: TVLang@OOPinJava2fair.conf.vn/~lang/lecture/java/TVLang@OOPinJava2.pdf · 2018-10-10 · §When we write programs in the Java language, all program data is wrapped in a class, whether

10/11/18

21

§ Test Program with RunPerson classpublic class RunPerson {

Person p; public RunPerson(){

p = new Person(); p.setName("T.V. Lang"); p.setBirthyear( 1959 ); System.out.print( "Name : " + p.getName() + " Birthyear : "

+ p.getBirthyear()); }public static void main(String args[]) {

new RunPerson();}

}

A.Prof. Tran Van Lang, PhD.