Example: Fibonacci Numbers

Similar documents
Recursion 1. Recursion is the process of defining something in terms of itself.

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

The return Statement

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

Instance Members and Static Members

Example: Count of Points

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University

1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248

Java Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Example: Count of Points

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Exercise: Singleton 1

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Chapter 4 Defining Classes I

Object-Oriented Programming Concepts

Creating an object Instance variables


Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Nested Loops. A loop can be nested inside another loop.

Notes on Chapter Three

Chapter 2: Java OOP I


Objects and Classes: Working with the State and Behavior of Objects

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Programming Languages and Techniques (CIS120)

ITI Introduction to Computing II

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

CHAPTER 7 OBJECTS AND CLASSES

Example. Password generator

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Object-Oriented Programming

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

ITI Introduction to Computing II

Programming II (CS300)

Container Vs. Definition Classes. Container Class

CHAPTER 7 OBJECTS AND CLASSES

More Relationships Between Classes

Static, Final & Memory Management

CS1004: Intro to CS in Java, Spring 2005

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 5: Methods CS2301

Programming II (CS300)

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Lecture 3. Lecture

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Programming II (CS300)

Programming Languages and Techniques (CIS120)

First IS-A Relationship: Inheritance

Lecture 6 Introduction to Objects and Classes

Java Object Oriented Design. CSC207 Fall 2014

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Chapter 5 Object-Oriented Programming

Software Development. Modular Design and Algorithm Analysis

Anatomy of a Class Encapsulation Anatomy of a Method

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

Comments are almost like C++

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

G Programming Languages - Fall 2012

CS11 Intro C++ Spring 2018 Lecture 1

ENCAPSULATION AND POLYMORPHISM

Example: Monte Carlo Simulation 1

1.00 Lecture 5. Objects

JAVA: A Primer. By: Amrita Rajagopal

Principles of Object Oriented Programming. Lecture 4

Object Oriented Programming

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

Exercise (Revisited)

CS/ENGRD 2110 FALL Lecture 4: The class hierarchy; static components

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects


1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b. Classes in Java Part III. Review. Static. Static (2) Example. Static (3) 1B1b Lecture Slides. Copyright 2004, Graham Roberts 1

Chapter 15: Object Oriented Programming

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

COURSE 2 DESIGN PATTERNS

CH. 2 OBJECT-ORIENTED PROGRAMMING

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

EMBEDDED SYSTEMS PROGRAMMING OO Basics

Methods. CSE 114, Computer Science 1 Stony Brook University

Chapter 4: Writing Classes

Object Oriented Programming with Java

CS18000: Programming I

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Lecture #6-7 Methods

Data Structures (list, dictionary, tuples, sets, strings)

Object oriented programming Concepts

INHERITANCE AND OBJECTS. Fundamentals of Computer Science I

Object Oriented Programming

Transcription:

Example: Fibonacci Numbers Write a program which determines F n, the (n + 1)-th Fibonacci number. The first 10 Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. The sequence of Fibonacci numbers can be defined by the recurrence relation F n = F n 1 + F n 2, where n 2 and F 0 = 0, F 1 = 1. Zheng-Liang Lu Java Programming 209 / 246

1... 2 public static int fib(int n) { 3 if (n < 2) 4 return n; 5 else 6 return fib(n 1) + fib(n 2); 7 } 8... This recursive implementation is straightforward. Yet, this algorithm isn t efficient since it requires more time and memory. Time complexity: O(2 n ) (Why?!) Zheng-Liang Lu Java Programming 210 / 246

Zheng-Liang Lu Java Programming 211 / 246

1... 2 public static double fibiter(int n) { 3 if (n < 2) 4 return n; 5 6 int x = 0, y = 1; 7 for (int i = 2; i <= n; i++) { 8 int z = x + y; 9 x = y; 10 y = z; 11 } 12 return y; // why not z? 13 } 14... So it can be done in O(n) time. It implies that the recursive one is not optimal. Could you find a linear recursion for Fibonacci numbers? You may try more examples. 1 1 See http://introcs.cs.princeton.edu/java/23recursion/. Zheng-Liang Lu Java Programming 212 / 246

Divide and Conquer For program development, we use the divide-and-conquer strategy 2 to decompose the original problem into subproblems, which are more manageable. For example, selection sort. Pros: easier to write, reuse, debug, modify, maintain, and also better facilitating teamwork 2 Aka stepwise refinement. Zheng-Liang Lu Java Programming 213 / 246

Computational Thinking Computational thinking is taking an approach to solving problems, designing systems and understanding human behavior that draws on concepts fundamental to computing. 3 solve problems: mathematical thinking design systems: engineering thinking 4 understand human behavior: scientific thinking 3 Read http: //rsta.royalsocietypublishing.org/content/366/1881/3717.full. 4 Design and evaluate a large and complex system that operates within the constraints of the real world. Zheng-Liang Lu Java Programming 214 / 246

https://en.wikipedia.org/wiki/file:the_computational_thinking_process.jpg Zheng-Liang Lu Java Programming 215 / 246

Computational Thinking Everywhere The essence of computational thinking is abstraction. An algorithm is an abstraction of a step-by-step procedure for taking input and producing some desired output. A programming language is an abstraction of a set of strings each of which when interpreted effects some computation. And more. The abstraction process, which is to decide what details we need to highlight and what details we can ignore, underlies computational thinking. The abstraction process also introduces layers. Well-defined interfaces between layers enable us to build large, complex systems. Zheng-Liang Lu Java Programming 216 / 246

Example: Abstraction of Computer System Zheng-Liang Lu Java Programming 217 / 246

Example: Methods as Control Abstraction Zheng-Liang Lu Java Programming 218 / 246

Abstraction (Concluded) Control abstraction is the abstraction of actions while data abstraction is that of data structures. One can view the notion of an object as a way to combine abstractions of data and actions. Zheng-Liang Lu Java Programming 219 / 246

1 class Lecture7 { 2 3 // Object Oriented Programming 4 5 } 6 7 // Key words: 8 class, new, this, static, null, extends, super, abstract, final, interface, implements, protected Zheng-Liang Lu Java Programming 220 / 246

Observation in Real World Look around. We can easily find many examples for real-world objects. For example, a person with a bottle of water. Real-world objects all have states and behaviors. What states can the object need? What behaviors can the object perform on the states? Identifying these states and behaviors for real-world objects is a great way to begin thinking in object-oriented programming. From now, OO is a shorthand for object-oriented. Zheng-Liang Lu Java Programming 221 / 246

Objects An object keeps its states in fields (or attributes) and exposes its behaviors through methods. Plus, we hide internal states and expose methods which perform actions on the aforesaid states. This is so-call encapsulation, which is one of OO features. 5 Before we create the objects, we need to define a new class as their prototype (or concept). 5 The rest of features in OO are inheritance and polymorphism, which we will see later. Zheng-Liang Lu Java Programming 222 / 246

Classes We often find many objects all of the same kind. For example, student A and student B are two instances of student. Every student needs a name and a student ID. Every student should do homework and pass the final exams. A class is the blueprint to create class instances which are runtime objects. In the other word, an object is an instance of some associated class. In Java, classes are the building blocks in every program. Once the class is defined, we can use this class to create objects. Zheng-Liang Lu Java Programming 223 / 246

Example: Points in 2D Coordinate 1 public class Point { 2 // data members: so called fields or attributes 3 double x, y; 4 } 1 public class PointDemo { 2 public static void main(string[] args) { 3 // now create a new instance of Point 4 Point p1 = new Point(); 5 p1.x = 1; 6 p1.y = 2; 7 System.out.printf("(%d, %d)\n", p1.x, p1.y); 8 9 // create another instance of Point 10 Point p2 = new Point(); 11 p2.x = 3; 12 p2.y = 4; 13 System.out.printf("(%d, %d)\n", p2.x, p2.y); 14 } 15 } Zheng-Liang Lu Java Programming 224 / 246

Class Definition First, give a class name with the first letter capitalized, by convention. The class body, surrounded by balanced curly braces {}, contains data members (fields) and function members (methods). Zheng-Liang Lu Java Programming 225 / 246

Data Members As mentioned earlier, these fields are the states of the object. Each field may have an access modifier, say public and private. public: accessible by all classes private: accessible only within its own class We can decide if these fields are accessible! In practice, all fields should be declared private to fulfill the concept of encapsulation. However, this private modifier does not quarantine any security. 6 What private is good for maintainability and modularity. 7 6 Thanks to a lively discussion on January 23, 2017. 7 Read http://stackoverflow.com/questions/9201603/ are-private-members-really-more-secure-in-java. Zheng-Liang Lu Java Programming 226 / 246

Function Members As said, the fields are hidden. So we provide getters and setters if necessary: getters: return some state of the object setter: set a value to the state of the object For example, getx() and gety() are getters; setx() and sety() are setters in the class Point. Zheng-Liang Lu Java Programming 227 / 246

Example: Point (Encapsulated) 1 public class Point { 2 // data members: fields or attributes 3 private double x; 4 private double y; 5 6 // function members: methods 7 public double getx() { return x; } 8 public double gety() { return y; } 9 10 public void setx(double new x) { x = new x; } 11 public void sety(double new y) { y = new y; } 12 } Zheng-Liang Lu Java Programming 228 / 246

Exercise: Phonebook 1 public class Contact { 2 private String name; 3 private String phonenumber; 4 5 public String getname() { return name; } 6 public String getphonenumber() { return phonenumber; } 7 8 public void setname(string new name) { name = new name; } 9 public void setphonenumber(string new phnnum) { 10 phonenumber = new phnnum; 11 } 12 } Zheng-Liang Lu Java Programming 229 / 246

1 public class PhonebookDemo { 2 3 public static void main(string[] args) { 4 Contact c1 = new Contact(); 5 c1.setname("arthur"); 6 c1.setphonenumber("09xxnnnnnn"); 7 8 Contact c2 = new Contact(); 9 c1.setname("emma"); 10 c1.setphonenumber("09xxnnnnnn"); 11 12 Contact[] phonebook = {c1, c2}; 13 14 for (Contact c: phonebook) { 15 System.out.printf("%s: %s\n", c.getname(), 16 c.getphonenumber()); 17 } 18 } 19 20 } Zheng-Liang Lu Java Programming 230 / 246

Unified Modeling Language 8 Unified Modeling Language (UML) is a tool for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems. Free software: http://staruml.io/ (available for all platforms) 8 See http://www.tutorialspoint.com/uml/ and http://www.mitchellsoftwareengineering.com/introtouml.pdf. Zheng-Liang Lu Java Programming 231 / 246

Example: Class Diagram for Point Modifiers can be placed before both fields and methods: + for public for private Zheng-Liang Lu Java Programming 232 / 246

Constructors A constructor follows the new operator. A constructor acts like other methods. However, its names should be identical to the name of the class and it has no return type. A class may have several constructors if needed. Recall method overloading. Constructors are used only during the objection creation. Constructors cannot be invoked by any object. If you don t define any explicit constructor, Java assumes a default constructor for you. Moreover, adding any explicit constructor disables the default constructor. Zheng-Liang Lu Java Programming 233 / 246

Parameterized Constructors You can provide specific information to objects by using parameterized constructors. For example, 1 public class Point { 2... 3 // default constructor 4 public Point() { 5 // do something in common 6 } 7 8 // parameterized constructor 9 public Point(double new x, double new y) { 10 x = new x; 11 y = new y; 12 } 13... 14 } Zheng-Liang Lu Java Programming 234 / 246

Self Reference You can refer to any (instance) member of the current object within methods and constructors by using this. The most common reason for using the this keyword is because a field is shadowed by method parameters. You can also use this to call another constructor in the same class by invoking this(). Zheng-Liang Lu Java Programming 235 / 246

Example: Point (Revisited) 1 public class Point { 2... 3 public Point(double x, double y) { 4 this.x = x; 5 this.y = y; 6 } 7... 8 } However, the this operator cannot be used in static methods. Zheng-Liang Lu Java Programming 236 / 246

Instance Members You may notice that, until now, all members are declared w/o static. These members are called instance members. These instance members are available only after the object is created. This implies that each object has its own states and does some actions. Zheng-Liang Lu Java Programming 237 / 246

Zheng-Liang Lu Java Programming 238 / 246

Static Members The static members belong to the class 9, and are shared between the instance objects. These members are ready once the class is loaded. For example, the main method. They can be invoked directly by the class name without using any instance. For example, Math.random() and Math.PI. They are particularly useful for utility methods that perform work that is independent of instances. For example, factory methods in design patterns. 10 9 As known as class members. 10 Design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. by Wikipedia. Zheng-Liang Lu Java Programming 239 / 246

Zheng-Liang Lu Java Programming 240 / 246

A static method can access other static members. (Trivial.) However, static methods cannot access to instance members directly. (Why?) For example, 1... 2 public double getdistancefrom(point that) { 3 return Math.sqrt(Math.pow(this.x that.x, 2) 4 + Math.pow(this.y that.y, 2)); 5 } 6 7 public static double measure(point first, Point second) { 8 // You cannot use this.x and this.y here! 9 return Math.sqrt(Math.pow(first.x second.x, 2) 10 + Math.pow(first.y second.y, 2)); 11 } 12... Zheng-Liang Lu Java Programming 241 / 246

Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling the constructor with no argument 11 // should be placed in the first line 12 this.x = x; 13 this.y = y; 14 } 15... 16 } Zheng-Liang Lu Java Programming 242 / 246

Exercise: Singleton In some situations, you may create the only instance of the class. 1 public class Singleton { 2 3 // Do now allow to invoke the constructor by other classes. 4 private Singleton() {} 5 6 // Will be ready as soon as the class is loaded. 7 private static Singleton INSTANCE = new Singleton(); 8 9 // Only way to obtain this singleton by the outside world. 10 public static Singleton getinstance() { 11 return INSTANCE; 12 } 13 } Zheng-Liang Lu Java Programming 243 / 246

Garbage Collection (GC) 12 Java handles deallocation 11 automatically. Timing: preset period or when memory stress occurs. GC is the process of looking at the heap, identifying if the objects are in use, and deleting those unreferenced objects. An object is unreferenced if the object is no longer referenced by any part of your program. (How?) Simply assign null to the reference to make the object unreferenced. Note that you may invoke System.gc() to execute the deallocation procedure. However, frequent invocation of GC is time-consuming. 11 Release the memory occupied by the unused objects. 12 http://www.oracle.com/webfolder/technetwork/tutorials/obe/ java/gc01/index.html Zheng-Liang Lu Java Programming 244 / 246

finalize() The method finalize() conducts a specific task that will be executed right before the object is reclaimed by GC. For example, closing files and terminating network connections. The finalize() method can be only invoked prior to GC. In practice, it must not rely on the finalize() method for normal operations. (Why?) Zheng-Liang Lu Java Programming 245 / 246

Example 1 public class Garbage { 2 private static int numofobjkilled = 0; 3 4 public void finalize() { 5 numofobjkilled++; 6 } 7 8 public static void main(string[] args) { 9 double n = 1e7; 10 for (int i = 1; i <= n; i++) 11 new Garbage(); // lots of unreferenced objects 12 System.out.println(numOfObjKilled); 13 } 14 } You may try different number for instance creation. The number of the objects reclaimed by GC is uncertain. Zheng-Liang Lu Java Programming 246 / 246