1 of 44

Objects and Classes

Object-Oriented Programming

2 of 44

Outline

  • Using a class: objects
  • Creating a class
    • private/public…
  • OOP concept: Abstraction
  • OOP concept: Encapsulation

Readings:

  • IPIJ: Ch.3.

Introduction to Java

2

3 of 44

Abstract data types

A data type is a set of values and �a set of operations on those values

Primitive types

  • values immediately map to machine representations
  • operations immediately map to machine instructions.

We want to write programs that process other types of data.

  • Colors, pictures, strings,
  • Complex numbers, vectors, matrices, graphs…

An abstract data type is a data type �whose representation is hidden from the client.

Objects and Classes

3

4 of 44

Object-oriented programming (OOP)

Class == Abstract Data Type

Object == Variables

OOP: create classes and manipulate the objects in your program

(i.e. create your own data types and use them in your program)

Clients can use ADTs �without knowing implementation details.

Our tasks:

  • How to create classes?
  • How to use classes and objects?

Objects and Classes

4

5 of 44

Using a class

How to construct new objects

  • Use the keyword new to invoke a constructor.
  • Use data type name to specify type of object.

How to apply operations to a given object

  • Use object name to specify which object.
  • Use the dot operator to indicate that an operation is to be applied.
  • Use a method name to specify which operation

Objects and Classes

5

6 of 44

Color ADT

6

7 of 44

Using color: monochrome luminance

7

8 of 44

Computing with color: grayscale

8

9 of 44

Picture Abstract Data Type

9

10 of 44

Picture client example: Grayscale filter

10

11 of 44

Picture client example: Grayscale filter

11

12 of 44

Objects in a program

12

  • One object created: c of class Color
  • Object variables: c in main() and c in lum()
  • c.getRed(), c.getGreen(), c.getBlue(): method of object c

  • lum(Color c): a function of class Luminance
  • Integer.parseInt(): a function of class Integer
  • StdOut.println(): a function of class StdOut
  • main(): Luminance program
  • Objects created: pic of class Picture
    • and implicitly pic’s Color objects
  • Object variables: pic, color, gray
  • pic.height(), pic.width(), pic.get(), pic.set(), pic.show(): method of object pic

  • Luminance.toGray(color): a function of class Luminance (static function)
  • main(): Grayscale program

13 of 44

Object equality

  • "==" and "!=" compares references (not objects) to see if they are refering to the same object.

Đại học Công nghệ - ĐHQG HN

More on Java

13

Integer b = new Integer(10);

Integer c = new Integer(10);

Integer a = b;

a==b is true�b==c is false

  • Use the equals() method to see if two objects are equal.

Integer b = new Integer(10);

Integer c = new Integer(10);

if (b.equals(c)) { // true };

14 of 44

Object equality

Method equals()

  • Pre-defined classes:
    • Ready to use

  • User-created classes:
    • equals(Object) must be defined, otherwise, it always returns false
    • This is overriding�(more on that later)

Đại học Công nghệ - ĐHQG HN

More on Java

14

Integer m1 = new Integer(10);

Integer m2 = new Integer(10);

System.out.print(m1.equals(m2));

class MyInteger {

private int value;

public boolean equals (Object other) {

….

return (value == other.value);

}

...

}

15 of 44

Object's life on the heap

  • Objects are created in the heap memory
    • a constructor is automatically called to initialize it
    • the set of parameters determine which constructor to call and the initial value of the object
  • Objects are manipulated via references
    • dot notation is used to access the object's instance variables and methods
  • when an object is no longer used, i.e. there's no more reference to it, it will be collected and freed by Java garbage collector.

Đại học Công nghệ - ĐHQG HN

More on Java

15

16 of 44

Object’s life on the heap

  • Constructors
    • Initialize instance variables
    • Called by new operator

    • No return value
    • Compiler provides a default constructor (empty body, empty parameter list) when none is defined.

Đại học Công nghệ - ĐHQG HN

More on Java

16

class Dog {

String name;

...

public Dog(String n) {

name = n;

}

public Dog(String n, int s) {

name = n;

size = s;

}

}

Dog dog1 = new Dog(“Bruno”);

Dog dog2 = new Dog(“Ben”, 2);

public Dog() {}

17 of 44

Object’s life on the heap

17

18 of 44

Object’s life on the heap

18

19 of 44

Object’s life on the heap

19

20 of 44

Object’s life on the heap

20

21 of 44

Object’s life on the heap

21

22 of 44

Garbage collection

  • To reclaim the memory occupied by objects that are no longer in use
  • Programmers don’t have to disallocate objects
  • Java Virtual Machine (JVM) performs automatic garbage collection
    • Method finalize() is called by JVM, not programmers.
    • Guarantee no memory leaks
  • However, there’s no guarantee when/whether an object is freed before the program terminates
    • Might not needed as memory is still available
    • Clean-up tasks must be done explicitly by other “clean-up” methods rather than finalize()

Đại học Công nghệ - ĐHQG HN

More on Java

22

More on Java

22

Đại học Công nghệ. ĐHQG Hà Nội

23 of 44

Classes and Objects

  • A classe is a blueprint to create objects (instantiate).
    • Classes are what we design and code. �Class definitions make up programs.
  • Objects are what are created (from a class) at run-time
  • “Data type – Variable” relation

OOP Concepts

23

24 of 44

Classes and Objects

  • A classe is a blueprint to create objects (instantiate).
    • Classes are what we design and code. �Class definitions make up programs.
  • Objects are what are created (from a class) at run-time
  • “Data type – Variable” relation

OOP Concepts

24

25 of 44

Objects

  • Object Identities
    • Java object ids, probably the address of the object
  • Object State 🡪 Attributes / Instant variables
    • (20lit, 0km/h,”143 WJT”)
  • Object Behavior 🡪 Methods
    • Operations/services performed on the object.
    • accelerate()...

OOP Concepts

25

26 of 44

Design a class

26

Picture

-image: BufferedImage

-jframe: JFrame

-width, height: int

+width(): int

+height(): int

+get(int, int): Color

+set(int, int, Color): void

+show(): void

+save(String): void

instance variables

methods

27 of 44

API, UML notation, Implementation

27

Picture

-image: BufferedImage

-jframe: JFrame

-width, height: int

+width(): int

+height(): int

+get(int, int): Color

+set(int, int, Color): void

+show(): void

+save(String): void

public final class Picture ... {

private BufferedImage image; // the rasterized image

private JFrame jframe; // on-screen view

private final int width, height;

...

public int height() {

return height;

}

public int width() {

return width;

}

public void show() {

if (jframe == null && !isDisposed) {

jframe = createGUI();

...

...

}

...

}

https://introcs.cs.princeton.edu/java/stdlib/Picture.java

API

UML

Implementation

API: Application Programming Interface.�A list of public instance variables and methods

UML notation: Unified Modelling Language�private members are shown with -public members are with +

28 of 44

Creating a class

28

Dog

-size: int

-name: String

+Dog(_name, _size)

+bark: void

+toString(): String

public class Dog {

private final String name;

private int size;

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

public void bark() {

if (size > 60) {

System.out.println("Wooof! Wooof!");

} else if (size > 14) {

System.out.println("Ruff! Ruff!");

} else {

System.out.println("Yip! Yip!");

}

}

public String toString() {

return "(" + name + ", " + size + ")";

}

}

The Dog class has an instance variable size that the bark() method uses to decide what kind of bark sound to make.

29 of 44

Access modifiers

29

Dog

-size: int

-name: String

+Dog(_name, _size)

+bark: void

+toString(): String

public class Dog {

private final String name;

private int size;

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

public void bark() {

if (size > 60) {

System.out.println("Woof! Woof!");

} else if (size > 14) {

System.out.println("Ruff! Ruff!");

} else {

System.out.println("Yip! Yip!");

}

}

}

Access modifiers:

public: accessible by any clients;

private: accessible only from within the class

final: value of the variable will not change once it is initiallized

Instance variables: name and size

30 of 44

Constructor

30

Dog

-size: int

-name: String

+Dog(_name, _size)

+bark: void

+toString(): String

public class Dog {

private final String name;

private int size;

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

public void bark() {

if (size > 60) {

System.out.println("Woof! Woof!");

} else if (size > 14) {

System.out.println("Ruff! Ruff!");

} else {

System.out.println("Yip! Yip!");

}

}

}

Constructors: special methods that create an object and provide a reference to that object.

When a client program uses the keyword new, Java will:

  • Allocate memory for the object
  • Invoke a constructor to initialize the instance variables
  • Return a reference to the newly created object

31 of 44

Constructors

31

public class Dog {

// default constructor

public Dog() { }

// parameterized constructor

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

// parameterized constructor / copy constructor

public Dog(Dog other) {

name = other.name;

size = other.size;

}

...

Compiler will provide an empty default constructor when the class has no constructors

Unlike some other languages, there is no copy constructor provided by default. �Write one yourself if you need it.

32 of 44

Calling another constructor

32

public class Dog {

// default constructor

public Dog() {

this(“Grumpy”, 2);

}

// parameterized constructor

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

// parameterized constructor / copy constructor

public Dog(Dog other) {

this(other.name, other.size);

}

...

use the keyword this to call another constructor

33 of 44

Instance methods

Instance methods can perform operations on instance variables.

  • no keyword static

33

Dog

-size: int

-name: String

+Dog(_name, _size)

+bark: void

+toString(): String

public class Dog {

private final String name;

private int size;

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

public void bark() {

if (size > 60) {

System.out.println("Wooof! Wooof!");

} else if (size > 14) {

System.out.println("Ruff! Ruff!");

} else {

System.out.println("Yip! Yip!");

}

}

public String toString() {

return "(" + name + ", " + size + ")";

}

}

The instance variable size affects the bark() method, which uses size to decide what kind of bark sound to make.

34 of 44

A test client

34

public class Dog {

private final String name;

private int size;

public Dog(String _name, int _size) {

name = _name;

size = _size;

}

public void bark() {

if (size > 60) {

System.out.println("Wooof! Wooof!");

} else if (size > 14) {

System.out.println("Ruff! Ruff!");

} else {

System.out.println("Yip! Yip!");

}

}

public String toString() {

return "(" + name + ", " + size + ")";

}

}

public class DogTestDrive {

public static void main(String[] args) {

Dog one = new Dog("One", 70);

Dog two = new Dog("Two", 8);

Dog three = new Dog("Three", 35);

one.bark();

two.bark();

three.bark();

}

}

%> java DogTestDrive

Wooof! Wooof!

Yip! Yip!

Ruff! Ruff!

35 of 44

Why “private” size and name?

  • What is wrong with this code?
    • It allows for�a supernatural dog
    • Object's data is exposed.

  • Exposed instance variables can lead to invalid states of objects

  • Can’t let that happen

Objects and Classes

35

class Dog {

int size;

...

}

Dog d = new Dog();

d.size = -1;

36 of 44

Why “private” size and name?

In order to protect the state of an object:

  • hide the instance variables from client code by declaring them private.
  • force everyone call setter methods, where we can protect objects from unacceptable changes.

36

public class Dog {

private int size;

public void setSize(int _size) {

if (_size > 0) size = _size;

}

public int getSize() {

return size;

}

...

hide size

setter

getter

37 of 44

Encapsulation

  • Encapsulation: to group related things together, so as to use one name to refer to the whole group.
    • Functions/procedures encapsulate instructions
    • Objects encapsulate data and related procedures

OOP Concepts

37

Picture

-image: BufferedImage

-jframe: JFrame

-width, height: int

+width(): int

+height(): int

+get(int, int): Color

+set(int, int, Color): void

+show(): void

+save(String): void

related components are inside the box

38 of 44

Information hiding

  • Information hiding: hide internal implementation details from outsiders
    • Outsiders see only interfaces
    • Programmers have the freedom in implementing the details of a system.
    • Hence, the ability to make changes to an object’s implementation without affecting other parts of the program

OOP Concepts

38

Picture

-image: BufferedImage

-jframe: JFrame

-width, height: int

+width(): int

+height(): int

+get(int, int): Color

+set(int, int, Color): void

+show(): void

+save(String): void

private variables/methods are NOT accessible from outside the class

components are hidden inside the box

39 of 44

Encapsulation/Information hiding

39

declaring all the instance variables in a class as private �and writing public methods in the class to set and get the values of the variables

public class Dog {

private int size;

public void setSize(int _size) {

if (_size > 0) size = _size;

}

public int getSize() {

return size;

}

...

hide size

setter

getter

  • Don't forget to check data validity in setters.

40 of 44

Class access control

Access modifiers:

    • public : Accessible anywhere by anyone
    • private : Only accessible within the current class
    • protected : Accessible only to the class itself and to its subclasses or other classes in the same “package” (more on this later)
    • default (no keyword): accessible within the current package (more on this later)

Objects and Classes

40

41 of 44

OOP Concept: Abstraction

  • Abstraction: to distill a complicated system down to its most fundamental parts and describe these parts in a simple, precise language.
    • naming the parts
    • explaining their functionality

41

42 of 44

OOP Concept: Abstraction

42

43 of 44

Four pillars of OOP

43

Abstraction

Encapsulation

Inheritance

Polymorphism

44 of 44

Summary

  • objects vs. classes
  • instances vs. object references
  • behaviour: methods
  • state: attributes, instance variables

  • encapsulation, information hiding
  • abstraction

44