65

OBJECT ORIENTED PROGRAMMING - Bangkok …tulip.bu.ac.th/~thirapon.w/gim/OOP_files/slide5.pdf* This is Javadoc comment. This comment is used with Javadoc program. * Fruit class has

  • Upload
    vumien

  • View
    223

  • Download
    1

Embed Size (px)

Citation preview

OBJECT ORIENTED PROGRAMMING

Thirapon Wongsaardsakul

WHAT?

• Procedural Programming

• Object Oriented Programming

PROCEDURAL PROGRAMMING

Main

Begin

doA()

doB()

x = doC()

if ( doD() )

End

doA()

Begin

doX()

h=doZ()

Eng

doX()

Begin

doM()

doN()

Eng

doZ()

Begin

doT()

return f

Eng

OOP

• Thinking of how a house is built.

• Two main benefits

• Independent behavior or modularity

• Code reuse

CLASS

• What is a class?

• How can we define a class in OOP?

• Class components

• Attributes

• Methods

EXAMPLES OF CLASSES• House as a class

• Location

• Area (square feet)

• Bed room

• Kitchen room

• etc.

• What can we do with a house?

• repaintHouse()

• addBathroom()

• destroy()

Properties

Methods

EXERCISE• Write attributes and methods of these given items

• Car

• Human

• Book

• Telephone

• Clock

• Pen

• Student

• Paper

CLASS VS. OBJECT• Is a human an object?

• Hair color?

• Male/female?

• Nationality?

• Is a computer an object?

• Desktop/laptop?

• CPU’s speed?

• Memory size?

OBJECT• Is A. Chonthorn a human object?

• Black hair

• Male

• Thai

• Is MacBook pro a computer object?

• Laptop

• Core i5 2.0 GHz

• 4 Gbytes

CLASS AND OBJECT RELATIONSHIP

Rubber stamp

FOUR KEY PRINCIPLES OF OOP

Abstraction Encapsoluation Inheritance Polymorphism

ABSTRACTION

• Ignore irrelevant items when defining attributes and methods of a class

FRUIT CLASS

• Please define attributes and methods based on what are really needed

Attributes•weight•cal/gram

Methods•totalCalories()

Consider these itemsHumanStudent

CLASS DECLARATION

<modifiers> class <class_name> {

[<attribute declarations>]

[<constructor declarations>]

[<method declarations>]

}

FRUIT.JAVA1. public class Fruit {

2. private double calories;

3. private double weight;

4. Fruit() {

5. calories = 500;

6. weight = 1;

7. }

8. public double calculateEnergy() {

9. return calories * weight;

10. }

11.}

CREATE AN OBJECT

• Fruit orange = new Fruit();

• Fruit grape = new Fruit();

INTRODUCTION TO BLUEJ• BuleJ is Java IDE with allowing a programmer to visualize objects that he/she creates

on the fly

• Built in effective debugging tools ever

EDITOR

INTERACT WITH OBJECT

UNIFIED MODELING LANGUAGE (UML)

• It is a model that describe a design or system of a software

• Why model?

• To test whether a design is working

• To reduce cost of development

• Designing an airplane

• Engineers must build several models to test before produce real items

CLASS DIAGRAM

• Class MyDate is represent a date data

• day/month/year

public class MyDate { public int day; public int month; private int year ;}

CLASS DIAGRAM: DEPENDENCY

public class MyDate { public int day; public int month; private int year ;}

public class TestMyDate{ public static void main(String[ ] args) { MyDate myDate = new MyDate(); }}

ENCAPSULATION

Abstraction Encapsulation Inheritance Polymorphism

ENCAPSULATION

• Hiding irrelevant details from user

• Making class less complicated

• For example

• Car

• Remote controller

• TV set

ENCAPSULATION EXAMPLE

• Try TestDialog.java

• It will pop up a dialog box and say “Hello” to you

CLASS VARIABLESpublic class MyDate { public int day; public int month; private int year ;}

public class TestMyDate{ public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.day = 5; myDate.month = 6; System.out.println("Today is " + myDate.day + "/" + myDate.month); }}

WHY ENCAPSULATION?public class MyDate { public int day; public int month; private int year ;}

public class TestMyDate{ public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.day = 5; myDate.month = 16; System.out.println("Today is " + myDate.day + "/" + myDate.month); }}

PRIVATE VARIABLE TYPEpublic class MyDate { public int day; public int month; private int year ;}

public class TestMyDate{ public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.day = 5; myDate.month = 16; System.out.println("Today is " + myDate.day + "/" + myDate.month + “/”

+ myData.year); }}

Error, private type cannot be accessed

PUBLIC METHOD

• The way to access class variables is closed

• If all class variables are private types, there must be public methods that can access these variables from outside world

METHOD DECLARATION

[return type] [method name] ( [type] [variable], ..., [type] [variable])

int power (int x)

void printToScreen(String message)

boolean frontIsClear()

SET CLASS VARIABLES

SET & GET

EXERCISE

• Modify class MyDate

• Detecting error when date is wrong

• 32/5/2004

• -1/1/2004

• 30/2/2004

• 29/2/2003

• 20/15/2004

CONSTRUCTOR

• It is a class method that is called when an object of the class is initiated

• It allows a programmer to assign values to variable members of the object

• Example

• new MyDate();

• The question is what are the values of day, month, and year

DEFAULT CONSTRUCTOR

public MyDate() { day = 1; month = 1; year = 2000; }

POLYMORPHISM

Abstraction Encapsoluation Inheritance Polymorphism

POLYMORPHISM

• It allows two methods to have the same name

• Two types of polymorphism

• Overloading

• Overriding (involving in inheritance)

OVERLOADING

• Multiple constructors

EXERCISE

• Use this class diagram to create a concrete java class

• Use TestBook.java to validate your code

OVERLOADING

• Create MyInteger with two overloading methods

MyInteger+power(in i: int) : int+power(in d:double) : double

INHERITANCE

Abstraction Encapsoluation Inheritance Polymorphism

INHERITANCE

• A class can reuse attributes and methods belonging to another class

CLASS HIERARCHY

Vehicle

Sedan Truck

Compact Mid Size Light Heavy

Altis Teana Vigo

SHAPE

OVERRIDING

Method printXY() of Shape is overridden by subclasses Circle and Square

OVERLOADING

Method area() of Circle is overloaded.

+area(in r : double) : double

is an utility function for calculating area of any radiuses.

JAVA DOCUMENTATION

• Why do you need it?

• I know that writing code explanation is one of the boring jobs for programmers

• Imagine that you can write your document while you are coding

• Java allows you to do that nicely

/**

* This is Javadoc comment. This comment is used with Javadoc program.

* Fruit class has 2 properties, 1 constructor, and 1 method.

*Javadoc will generate HTML files with this comment.

* @version 1.0

* @author Thirapon Wongsaardsakul

*/

public class Fruit {

private int weight, calorie;

/** This constructor will create a new object Fruit with assigned parameters.

* @param w weight of this fruit.

* @param cal how much calorie this fruit has per 1 gram.

*/

public Fruit (int w, int cal) {

weight = w;

calorie = cal;

}

/**

* This method will find total calories of the fruit

* @return the value of total calories

*/

public int total_cal () {

return weight * calorie;

}

} // class fruit

Javadoc comments

EXERCISE

• Please read how to create Java documentation in book chapter 3

SENDING DATA TO METHOD

• Pass by value

• Pass by reference

VARIABLE SCOPE

• Member variable

• Method variable

• Local variable

PROGRAMMING HAND ON

***Result from TestVehicle.java***

Creating a vehicle with a 10,000kg maximum load.

Add box #1 (500kg) : true

Add box #2 (250kg) : true

Add box #3 (5000kg) : true

Add box #4 (4000kg) : true

Add box #5 (300kg) : false

Vehicle load is 9750.0 kg

STUDENT AND COURSE

• Class that keeps student information

• A student can register to many courses

• A grade can be calculated for each course

THINK ABOUT DIAGRAM

• Noun

• Student

• Course

• Grade

• Verb

• Keeping student information

• Register to a course

• Calculate grade

CLASS DIAGRAM DESIGN

CLASS DIAGRAM

Use TestStudent.java to verify your code

CONSTRUCTOR

• If you do not write a constructor, java will put a default constructor for you

• If you write a constructor for a class, java will not insert the default constructor

COMPILER INSERTS DEFAULT CONSTRUCTOR

class Table{

public String name;

}

public class TestConstructor{

public static void main(String[] args) {

Table t = new Table();

}

}

Class Table {public Table(){}...

}

COMPILER WILL NOT INSERT ANY CONSTRUCTORclass Table{

public String name;

public Table(String name){

this.name = name;

}

}

public class TestConstructor1{

public static void main(String[] args) {

Table t = new Table();

}

}

Error?

NO DEFAULT CONSTRUCTORclass Table{

public String name;

public Table(String name){

this.name = name;

}

}

public class TestConstructor2{

public static void main(String[] args) {

Table t = new Table("Glass Table");

}

}

Error?

WILL THIS CODE COMPILE?class Table{

public String name;

public Table() {

name = "none";

}

public Table(String name){

this.name = name;

}

}

public class TestConstructor3{

public static void main(String[] args) {

Table t = new Table("Glass Table");

Table t1 = new Table();

}

}

Please do not forget to write default constructor every time you create a class

CONSTRUCTOR AND INHERITANCE RELATIONSHIP

Student(String, String) is called

SUPER()

• You can activate superclass’s constructor by using super()

INSTANCEOFclass Vehicle { }

class Car extends Vehicle{ }

class Convertible extends Car{ }

public class TestInstanceof {

public static void main (String args []){

Convertible Camry = new Convertible();

if (Camry instanceof Vehicle)

System.out.println("Yes, Camry is a vehicle");

if (Camry instanceof Car)

System.out.println("Yes, Camry is a car");

if (Camry instanceof Convertible)

System.out.println("Yes, Camry is a convertible car");

}

}

---------- Java Output----------

Yes, Camry is a vehicle

Yes, Camry is a car

Yes, Camry is a convertible car

ASSIGNMENT 4

• Programming Problem 4 in chapter 3

• Due next week