0% found this document useful (0 votes)
28 views

Java-OOP-data-abstraction-emoon

KAIST Data Structure ppt

Uploaded by

[HA] Nights
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java-OOP-data-abstraction-emoon

KAIST Data Structure ppt

Uploaded by

[HA] Nights
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Basic building blocks

• Built-in types of data


• Conditionals and loops
• Functions
• OOP
• Data Abstraction

Robert Sedgewick | Kevin Wayne


Building blocks of
Java
OOP
https://introcs.cs.princeton.edu/java/31datatype/

2
Why OOP?
Essential features of OOP
• Abstraction
• Applying the abstraction paradigm to the design of data
structures gives rise to abstract data type (ADTs).
• An ADT specifies what each operation does, but not how it
does it; expressed by an interface.
• An ADT is realized by a concrete data structure, which is
modeled in Java by a class.

• Encapsulation to hide information to make programs robust


• Facilitate separate development of clients and data type
implementations.
3

• Modularity: e.g., Libraries to reuse code.


©Robert
2014Sedgewick
Goodrich,| Tamassia,
Kevin Wayne
Goldwasser
Abstract data types (ADTs)
A data type is a set of values and a set of operations defined 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.
• Complex numbers, vectors, matrices,
• ...

Robert Sedgewick | Kevin Wayne


Data abstraction
An ADT is a mathematical model of a data structure that specifies the
type of data stored, the operations supported on them, and the
types of parameters of the operations.

An ADT specifies what each operation does, but not how it does it.

In Java,
• An ADT can be expressed by an interface, which is simply a list of
method declaration, where each method has an empty body.

• An ADT is realized by a concrete data structure, which is modeled


in Java by a class.
• A class specifies how the operations are performed in the body
of each method.
• i.e., a Java class implement an interface. 5

Robert Sedgewick | Kevin Wayne Also see Goodrich et al (p. 62)


Object-Oriented Programming (OOP)
• OOP involves programming using objects.

• A class serves as the primary means for abstraction in OOP.

• A class is the blueprint from which individual objects are


created.
• Every object is an instance of a class.

• A class defines the state and behavior of objects.

Robert Sedgewick | Kevin Wayne Also see Goodrich et al (pp. 5 – 16)


Object-oriented programming (OOP)
Object-oriented programming (OOP).
• Create your own data types.
An object holds a data type value.
• Use them in your programs (manipulate objects).
Variable names refer to objects.

Examples (stay tuned for details)

data type set of values examples of operations

String sequence of characters length, substring, compare C A T A G C G C

Best practice: Use abstract data types (representation is hidden from the client).

Impact: Clients can use ADTs without knowing implementation details.


• This lecture: how to write client programs for several useful ADTs
• Next lecture: how to implement your own ADTs
7

Robert Sedgewick | Kevin Wayne


Building blocks of
Java
Data abstraction
• Using Abstract Data Types
https://introcs.cs.princeton.edu/java/31datatype/

8
Strings
We have already been using ADTs!
defined in terms of its ADT
A Stringis a sequence of Unicode characters. values (typical)
In the Java programming language, strings are objects.

• Java's String ADT allows us to write Java programs that


manipulate strings.
• The exact representation is hidden (it could change and our
programs would still work).

Robert Sedgewick | Kevin Wayne


API, clients, & implementations
Client API Implementation

Client A contract between the client and Java code that


A program that uses the implementation implements the methods
methods specified in in an API, kept by
convention in a file with
API.
the library name and
a .java extension.

10

Robert Sedgewick | Kevin Wayne


String ADT & API
Java's ADT allows us to write Java
programs that manipulate strings.

The behavior of a data type is


specified in an API (Application
Programming Interface), which is a
list of constructor and instance
methods (operations).

O perations (API)

11
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

Robert Sedgewick | Kevin Wayne


Client:
Using a data type—constructors and methods
To use a data type, you need to know:
• Its name (capitalized, in Java).
• How to construct new objects.
• How to apply operations to a given object.
To construct a new object
• Use the keyword new to invoke a
constructor.
• Use data type name to specify type of
object.
To apply an operation (invoke an instance method)
• 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.
12

Robert Sedgewick | Kevin Wayne


String client example
You want to know whether a given string is a palindrome or
not.

A palindrome is a word, number, phrase, or other sequence


of characters which reads the same backward as forward.

Examples:
noon, mom, dad, level, kayak, refer.

The longest palindromic word in the Oxford English Dictionary is


the onomatopoeic tattarrattat, coined by James Joyce in Ulysses (1922) for a
knock on the door.
https://en.wikipedia.org/wiki/Palindrome 13

Robert Sedgewick | Kevin Wayne


String client example
public static boolean isPalindrome(String s) {
int n = s.length(); 0 1 2 3
for(int i=0; i<n/2; i++) {
if(s.charAt(i) != s.charAt(n-1-i)) n o o n
return false;
}
return true;
}

We can write clear and simple client code that uses numerous
instance methods specified in the API without knowing the internal
implementation of those methods.

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html 14

Robert Sedgewick | Kevin Wayne elice>Week 2-1> Palindrome


OOP context for strings
Genomics. Represent genome as a string over A C T G alphabet.
A gene is a substring of a genome.

Possible memory representation of String genome = new String("aacaagtttacaagc");

String s = genome.substring(1, 5);

String t = genome.substring(9, 13);


x genome t s

a a c a a g t t t a c a a g c x 15 x+9 4 x+1 4

memory length
address
Implications
• A constructor creates an object and returns to the client a reference to
that object, not the object itself (i.e., reference type).
• s and t are different strings that have the same value "acaa".
• (s == t) is false (because it compares addresses). 15

• (s.equals(t)) is true (because it compares character sequences).


Robert Sedgewick | Kevin Wayne
Pop quiz on String
//What does the following code fragment print?

//create a string object using new keyword.


//a new object is created regardless of whether the content is the same or not.
String s1 = new String("Cat");
String s2 = new String("Duckling");
String s3 = new String("Cat");

if(s1 == s3) System.out.println("Same");


else System.out.println("Different");

String s4 = "Cat"; //creates a string using string literal.


String s5 = "Cat"; //If an object with the same content exists,
//then the reference of that object is returned.
16

if(s4 == s5) System.out.println("Same");


else
Robert Sedgewick | Kevin Wayne System.out.println("Different");
Check point
1. What does API stand for?

2. What is an API?

3. What does the term a client refer to?

4. What does the term implementation refer to?


Robert Sedgewick | Kevin Wayne
Building blocks of
Java
Data abstraction
• Creating Abstract Data Types

https://introcs.cs.princeton.edu/java/32class/
19
API, clients, & implementations
Client API Implementation

Client A contract between the client and Java code that implements
A program that uses the implementation the methods in an API, kept
by convention in a file with
methods specified in
the library name and a .java
API. extension.

1) Specify an API.
The purpose of the API is to separate clients from implementations, to
enable modular programming.

The API specifies the behavior of an ADT.

Begin with a simple test client that uses the API.


20
2) Implement a Java class that meets the API specification.
3) Develop multiple test clients to validate the design decisions made in the
first
Robert two steps.
Sedgewick | Kevin Wayne
Implementation: Classes & Objects
To create a class, you need to provide code that
• Defines the set of values (instance variables). In Java, those are critical members
• Implements operations on those values of a class.
(methods).
A Java class
• Creates and initialize new objects (constructors).
instance variables
Instance variables
constructors
• Represent the data associated with an object of a class.
• Each instance of a class maintains its own set of
instance variables.
methods
Methods
•Can perform operations on instance variables.
•Accessor method; update method
Constructors
•Like a method with the same name as the type. test client

•No return type declaration.


•Create an instance of a class by using the new
operator with a method that has the same name as 21
the class.

Robert Sedgewick | Kevin Wayne


Crash course in complex numbers
A complex number is a number of the form a + bi where a and b are real and i = −1

Complex numbers are a quintessential mathematical


abstraction that have been used for centuries to give insight
into real-world problems not easily addressed otherwise.

To perform algebraic operations on complex numbers, use real


Leonhard Euler A. L. Cauchy
algebra, replace i 2 by −1 and collect terms. 1707−1783 1789−1857
• Addition example: (3 + 4i ) + (−2 + 3i ) = 1 + 7i .
• Multiplication example: (3 + 4i ) x (−2 + 3i ) = −18 + i .
Example: | 3 + 4i | = 5
-6 + 9i – 8i + 12i2
The magnitude or absolute value of a complex number a + bi is | a + bi | = 𝑎2 + 𝑏2 .

Applications: Signal processing, control theory, quantum mechanics, analysis of algorithms...


22

Robert Sedgewick | Kevin Wayne


API: ADT for complex numbers
A complex number is a number of the form a + bi where a and b are real and i = −1

An ADT allows us to write Java programs that manipulate complex numbers.


complex number 3 + 4i −2 + 2i
Values real part 3.0 −2.0
imaginary part 4.0 2.0

API
(operations)

23

Robert Sedgewick | Kevin Wayne


A simple test client
Best practice. Begin by implementing a simple test client.

public static void main(String[] args) {


Complex a = new Complex(3.0, 4.0);
System.out.println("a = " + a);

Complex b = new Complex(-2.0, 3.0);


System.out.println("b = " + b);

a = 3.0 + 4.0i
System.out.println("c = " + a.times(b));
b = -2.0 + 3.0i
a * b = -18.0 + 1.0i
System.out.println("Re(a) = "+a.re());
System.out.println("Im(a) = "+a.im());
} What we expect,
once the implementation is done.

24

Robert Sedgewick | Kevin Wayne elice>Week 2-1> Complex numbers


Complex number data type implementation:
Instance variables
Instance variables define data-type values. instance variables
constructor

Values
methods

public class Complex {


private final double re; Those instance variables are final; because
you expect the values are not gonna test client
private final double im; change in this case.

….

complex number 3 + 4i −2 + 2i
real part 3.0 −2.0
imaginary part 4.0 2.0

Key to OOP. Each object has instance-variable values.


25

Robert Sedgewick | Kevin Wayne


Complex number data type implementation:
Constructor
Instance variables define data-type values. instance variables
constructor

Constructors create and initialize new objects. Values


methods

public class Complex {


private final double re; Those instance variables are final; because
you expect the values are not gonna test client
private final double im; change in this case.

// Constructor
public Complex(double re, double im) {
this.re = re; //this refers to the object known as thing in the caller's context.
this.im = im; //set the instance variable equal to argument.
}
} references to instance variables, which are not declared within the constructor

Clients use new to invoke constructors.


• Pass arguments as in a method call.
• Return value is reference to new object. 26

Complex a = new Complex(3.0, 4.0);


Robert Sedgewick | Kevin Wayne
The Keyword this
Within an instance method (or constructor), the keyword this is
automatically defined as a reference to the instance upon which the
method was invoked.

There are three common uses:


1. To store the reference in a variable, or send it as a parameter
to another method that expects an instance of that type as an
argument.
2. To differentiate between an instance variable and a local
variable with the same name.
3. To allow one constructor body to invoke another constructor
body.

27

©Robert
2014Sedgewick
Goodrich,| Kevin
Tamassia,
WayneGoldwasser Also see Goodrich et al (p.15)
Check point

public void Complex(double real) {


re = real;
im = 0.0;
}

We wrote a constructor that takes a double value as its argument and


creates a Complex number with that value as the real part and no
imaginary part as shown above.

Would be the statement Complex c = new Complex(1.0) compiled?

28

Robert Sedgewick | Kevin Wayne


Complex number data type implementation:
Methods
instance variables
Methods define data-type operations (implement APIs).
constructors

public class Complex Java keyword "this" is a


{ methods
reference to "this object"
... and is implicit when an
public Complex plus(Complex b) instance variable is directly
{ might also write "this.re"
referenced test client
double real = re + b.re;
double imag = im + b.im;
a = v + wi
return new Complex(real, imag);
} b = x + yi
public Complex times(Complex b) a × b = vx + vyi + wxi + wyi 2
{ = vx − wy + (vy + wx)i
double real = re * b.re - im * b.im;
double imag = re * b.im + im * b.re; API
return new Complex(real, imag);
}
public double abs()
{ return Math.sqrt(re*re + im*im); }
public String toString()
{ return re + " + " + im + "i"; }
...
} 30

Robert Sedgewick | Kevin Wayne


Complex number data type implementation
text file named public class Complex
Complex.java {
private final double re;
private final double im; instance variables
public Complex(double real, double imag)
{ re = real; im = imag; } constructor
public Complex plus(Complex b)
{
double real = re + b.re;
double imag = im + b.im;
return new Complex(real, imag);
}
public Complex times(Complex b)
{
Instance methods
not “static” double real = re * b.re - im * b.im;
double imag = re * b.im + im * b.re;
return new Complex(real, imag);
}
public double abs()
{ return Math.sqrt(re*re + im*im); }
public String toString()
{ return re + " + " + im + "i"; }

The entire code available on elice>2-1>Complex number 31

Robert Sedgewick | Kevin Wayne


Instance methods vs. Static methods
The purpose of an instance method is to
operate on data-type values.

Static methods can be called without a.times(b)


creating an instance of the class.

Instance methods have all of the


properties of static methods:
• arguments are passed by value, method
names can be overloaded, they may have
a return value.

• an additional property that characterizes


instance methods: each invocation is
associated with an object.
32

Robert Sedgewick | Kevin Wayne


Access Control Modifiers
• The public class modifier designates that all classes may access the
defined aspect.

• The protected class modifier designates that access to the defined


aspect is only granted to classes that are designated as subclasses of
the given class through inheritance or in the same package.

• The private class modifier designates that access to a defined


member of a class be granted only to code within that class.
• Used to organize the computation and not available to clients.

• When a variable or method of a class is declared as static, it is


associated with the class as a whole, rather than with each individual
instance of that class.
33

©Robert
2014Sedgewick
Goodrich,| Kevin
Tamassia,
Wayne
Goldwasser
Scope
• The scope of instance and static
variables is the entire class
regardless of where the variables
are declared.

• If a local variable has the same


name as a class variable, the
local variable takes precedence
and the instance variable with
the same name is hidden.

34

Robert Sedgewick | Kevin Wayne


Summary: the scope of variables

variable purpose Scope


Parameter To pass value from client to method Method
Local For temporary use within method Block
To hold data-type value for objects
instance Class
in a class
static Shared by all objects of the class Class

35

Robert Sedgewick | Kevin Wayne


OOP summary
Object-oriented programming (OOP)
• Create your own data types (sets of values and ops on them).
• Use them in your programs (manipulate objects).
OOP helps us simulate the physical world
• Java objects model real-world objects.
• Not always easy to make model reflect reality.
• Examples: genome…. T A G A T G T G C T A G C

OOP helps us extend the Java language


• Java doesn't have a data type for every possible application.
• Data types enable us to add our own abstractions.
• Examples: Complex numbers,....
36

Robert Sedgewick | Kevin Wayne


Building blocks of
Java
More example

37
Client
// sample client
public static void main(String[] args) {
Student std1 = new Student("Harry", "Potter", "101", "Computer Science");
Student std2 = new Student("Hermione", "Granger", "1010", "Computational Biology");

}

• Java automatically invokes a constructor when a client program


uses the keywords new.

• Each time that a client invokes a constructor, Java automatically


• Allocates memory for the object
• Invokes the constructor code to initialize the instance variables
• Returns a reference to the newly created object

38

Robert Sedgewick | Kevin Wayne


Client
// sample client
public static void main(String[] args) {
Student std1 = new Student("Harry", "Potter", "101", "Computer Science");
Student std2 = new Student("Hermione", "Granger", "1010", "Computational Biology");
System.out.println(std1.getID());
System.out.println(std1); How do we specify which object’s
System.out.println(std2); instance variables we want to use?
std2.changeMajor("Biochemistry");
System.out.println(std2); }

101
Computer Science Harry Potter
Computational Biology Hermione Granger
Biochemistry Hermione Granger

• Each class can define its own main( ) method for unit testing and debugging.
• At a minimum, the test client should call every constructor and instance methods
in the class. 39

Robert Sedgewick | Kevin Wayne


API
To specify the behavior of an ADT, we specify an API.

public class Student


Student(String first, String last, String id_num, String major)
String getID( ) Return id_num
String getMajor( ) Return major
Void changeMajor(String major) Update the value of major
String toString( ) String representation of a data type

40

Robert Sedgewick | Kevin Wayne


Student.java
import java.util.*;

public class Student {


private String first; // first name
private String last; // last name
private String id_num; // student ID number Instance variables
private String major; // major

// construct a new student with given fields


public Student(String first, String last, String id_num, String major) {
this.first = first;
this.last = last;
this.id_num = id_num;
this.major = major;
}

public String getID() { //an accessor method returns information to the


caller without changing any instance variables
return id_num;
}

public String getMajor() { //an accessor method


return major;
}
public void changeMajor(String major) { //an update method may change one or
more instance variables when called.
this.major = major;
}
}
Robert Sedgewick | Kevin Wayne
toString()
• We implement toString() that returns a string representation of this object.
Check point—Classes & Objects
1) Create a Student object that stores the following data:
• first name: Ron
• last name: Weasley
• id_num: 1020
• Major: Astronomy

2) Implement a method that updates the student’s first


name to a given value of String.

3) Change Ron Weasley’s first name to Ginny.


42

Robert Sedgewick | Kevin Wayne


Check point
4) Some students do not declare a major when entering
university. For those students, you want to assign the value
“Undecided” to their major field without giving that value
from the client as follows.
Student std4 = new Student("Oliver", "Wood", "1012");

Write the code to do so in the Student class.

44

Robert Sedgewick | Kevin Wayne


Basic building blocks
• Built-in types of data
• Conditionals and loops
• Functions
• OOP
• Data Abstraction

Robert Sedgewick | Kevin Wayne


Exercise sessions
Check information about student groups on KLMS.
• Which group you belong to.
• Who your TA is.
• Where your group should sit in this classroom.

For every exercise session,


• Please sit in your group.
• Bring your laptop or tablet so that you can submit your
complete work to KLMS.
• If you can’t do so, it is imperative that you should let your TA
no later than Tuesday night. (Not right before the class starts!
Or during the exercise!)
47

Robert Sedgewick | Kevin Wayne

You might also like