CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Logic & program control part 2: Simple selection structures.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Animation Mrs. C. Furman. Animation  We can animate our crab by switching the image between two pictures.  crab.png and crab2.png.
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 10.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Java Programming, 3e Concepts and Techniques Chapter 2 - Part 2 Creating a Java Application and Applet.
***** SWTJC STEM ***** Chapter 2-2 cg Identifiers - Naming Identifier, the name of a Java programming component. Identifier naming rules... Must.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 2 - Using Objects.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Working With Objects Tonga Institute of Higher Education.
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Building java programs, chapter 3 Parameters, Methods and Objects.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
CSC 142 Computer Science II Zhen Jiang West Chester University
BOOLEAN OPERATIONS AND CONDITIONALS CHAPTER 20 1.
CSC 142 H 1 CSC 142 Standard input/output. CSC 142 H 2 Console Ouput  Use the static PrintStream object out in System System.out.println("Hello, world");
Expressions and Order of Operations Operators – There are the standard operators: add, subtract, divide, multiply – Note that * means multiply? (No times.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
OOP Basics Classes & Methods (c) IDMS/SQL News
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
A Sample Program #include using namespace std; int main(void) { cout
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Chapter 2 Basic Computation
Introduction to Computer Science / Procedural – 67130
Lecture 5: Some more Java!
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
Chapter 2 Programming Basics.
Object based programming in Java
Object Oriented Programming in java
Java objects: a first view
Object based programming in Java
CSC 111 Exam 3 Review Fall 2005.
Special instance methods: toString
IAT 800 Foundations of Computational Art and Design
Just Enough Java 17-May-19.
Problem 1 Given n, calculate 2n
Presentation transcript:

CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]

CSC 142 C 2 What we have seen so far  A class is made of  instance fields: attributes of the class objects  instance methods: behavior of the class objects (=what objects can do).  instance methods+fields=instance members  Some members are public (available to anyone=interface), some are private (available inside of the class only=implementation details)  To create an object of the class type, use ClassName myObject = new ClassName(); //creates an instance of ClassName

CSC 142 C 3 Another example import java.awt.Color; // Color class import uwcse.graphics.*; public class SomeGraphics{ // instance fields private GWindow window=new GWindow(); private Oval circle1=new Oval(); private Oval circle2=new Oval(); // constructor public SomeGraphics(){ // circle1 is blue, circle2 red circle1.setColor(Color.blue); circle2.setColor(Color.red); // move circle2 to the right by 80 pixels circle2.moveBy(80,0); window.add(circle1); window.add(circle2); } }

CSC 142 C 4 java.awt  A (huge) package to do graphics (awt stands for abstract windowing toolkit)  Color is a class that contains some predefined colors (you can also define your own colors, check the class documentation)  We could have also written to import the full package  import java.awt.*;  Note: With the above, we get access to all the classes in java.awt, but not the content of any package in java.awt

CSC 142 C 5 Initializing instance fields  Initializing means giving a value to something for the first time.  Instance fields can be directly initialized when declared private Oval circle1 = new Oval();  If not, an instance field referring to an object is automatically initialized to null private GWindow w; // w is null  Using a null reference to call a method is an error. w.doRepaint(); // error! Note: doRepaint means redisplay the window  Before using an instance field, make sure that it refers to an actual object.

CSC 142 C 6 references and assignment (1)  Consider public SomeGraphics(){ // circle1 is blue, circle2 red circle1.setColor(Color.blue); circle2.setColor(Color.red); // move circle2 to the right by 80 pixels circle2.move(80,0); circle2 = circle1; window.add(circle1); window.add(circle2); }  What happens?

CSC 142 C 7 references and assignment (2)  Before executing circle2 = circle1 circle1 circle1:Oval circle2 circle2:Oval  circle2 = circle1 circle1 :Oval circle2 circle2:Oval X  The object that circle2 referred to can't be accessed anymore. The memory it uses is freed by the JVM garbage collector.  Only 1 blue circle appears in window Note: if 2 or more references refer to the same object, drop the object reference in the UML notation

CSC 142 C 8 Swapping colors (1)  Add an instance method to the SomeGraphics class to swap the colors of the 2 circles  method swapColors: make it public  swapColors doesn't require any input. Write swapColors()  swapColors doesn't give back a result. Write void to the left of the method name. public void swapColors() { // what should we write? }

CSC 142 C 9 Swapping colors (2)  Is this OK? Color color1 = circle1.getColor(); Color color2 = circle2.getColor(); color1 = color2; // line 1 color2 = color1; // line 2 circle1.setColor(color1); circle2.setColor(color2); color1 color1:Color color2 color2:Color Before line 1 and 2 color1 color2 :Color After line 1 and 2

CSC 142 C 10 Swapping colors (3)  Need a 3 rd variable: replace line 1 and 2 with Color temp = color2; // line 1 color2 = color1; // line 2 color1 = temp; // line 3 color1 color1:Color color2 temp :Color after line 1 color2 color1 :Color temp temp:Color after line 2 color2 color2:Color color1 temp :Color after line 3

CSC 142 C 11 Swapping colors: code public class SomeGraphics { // instance fields, constructor as before... public void swapColors() { // colors of the circles Color color1=circle1.getColor(); Color color2=circle2.getColor(); // swap the colors Color temp = color2; color2 = color1; color1 = temp; // repaint with the new colors circle1.setColor(color1); circle2.setColor(color2); window.doRepaint(); } } color1, color2 and temp are defined inside of the method. They are called local variables. More on this later.

CSC 142 C 12 Designing classes  Example: a library member  The problem (unrealistically simple): Library member identified with SSN Only one book can be borrowed No time limit to return a book Book identified by its title  Analyze the problem nouns=objects, e.g. library member, book, SSN verbs=methods, e.g. borrow, return

CSC 142 C 13 LibaryMember class  Two private instance fields  ssn  book  Three public methods  constructor  returnBook  borrowBook LibraryMember ssn book LibraryMember returnBook borrowBook The class diagram is incomplete (e.g., no type for the instance fields, no information about the methods)

CSC 142 C 14 Instance field: ssn  An integer: int.  In Java, for efficiency reasons, some types are not object types: boolean for logical variables (true, false), int for integers (e.g., -1, 36,…), double for floating point numbers (e.g., 1.134, 0.23e-11,…), char for characters (e.g. 'a', '!', …)  write int ssn; // with the instance fields ssn = ; // e.g. in the constructor // don't use new  More on this later.

CSC 142 C 15 Instance field: book  need a Book class  instance field: title of type String (class available in java to manipulate text)  instance method: constructor. To construct a book, need a String for the title. Pass the String as a parameter to the constructor. Book String title Book(String)

CSC 142 C 16 Interlude: String class  Available in the package java.lang  Using String objects  for String literals, use double quotes "Washington State"  to create a String, use a String constructor String country = new String("USA");  how is this different? String country = "USA";  to get the number of characters in a String int n = state.length(); // n is 5 if // state is "Idaho"  Check the documentation

CSC 142 C 17 Book class import java.lang.String; // unnecessary. java.lang.* is always imported. public class Book{ private String title; public Book(String bookTitle) { // use the String constructor title = new String(bookTitle); // Does title=bookTitle do the same thing? }  To instantiate the Book class Book someBook = new Book("The grapes of wrath");

CSC 142 C 18 LibraryMember class constructor  To construct a LibraryMember, need an ssn  The constructor needs an input parameter, namely an int.  Initially, the LibraryMember has not borrowed a Book. book should be null.  Code (inside the LibraryMember class) public LibraryMember(int someSSN) { ssn = someSSN; // Do we need to set book to null? }

CSC 142 C 19 Instance method: returnBook (1)  Input: none  Output: did the operation succeed? (need to have a book initially). Return a boolean (true if success, false if failure).  Code (inside the LibraryMember class) public boolean returnBook() { // What do we write?...  Can the LibraryMember return a Book?  Yes, if book is not null: set book to null  No, if book is null.

CSC 142 C 20 Conditionals: a first view  General structure if (condition) { statement1; statement2; } else /*can be omitted if no else case*/ { statement3; statement4; } condition must be a boolean. It is an error to omit the parentheses executed if condition is false executed if condition is true If there is only one statement after the if or the else, the braces { and } after the if or the else may be omitted.

CSC 142 C 21 Equality and relational operators  All relations are boolean expressions. They evaluate to true or false.  equal and not equal x == y // is x equal to y? x != y // is x not equal to y? It is a syntax error to write a condition as x=y instead of x==y  ordering x < y // is x less than y? x >=y // is x greater than or equal to y? x > y // is x greater than y? x <=y // is x less than or equal to y?

CSC 142 C 22 What can you compare?  use ==, !=, =, with numbers and characters (e.g., int, double, char). With booleans only == and != are valid.  Don't compare objects with ==, !=, …except when comparing to null. See later.

CSC 142 C 23 Instance method: returnBook(2)  Write within the LibraryMember class public boolean returnBook() { if (book != null) //There is a book { book=null; System.out.println("book returned"); return true; } else // There is no book { System.out.println("Can't return a book"); System.out.println("You don't have a book"); return false; } }

CSC 142 C 24 Console output in Java  Use the out object in java.lang.System  System: a class to access low level system objects and methods (e.g. I/O functionalities)  out: PrintStream object. It comes with methods to display text in a console window (i.e., not a graphics window), e.g. print: print a String println: same as print but add a newline // The following prints Hello, world! System.out.print("Hello, "); System.out.print("world!"); // The following prints Hello on one line and // Good bye on the next line System.out.println("Hello"); System.out.println("Good bye");

CSC 142 C 25 return statement  In a method  syntax return expression;  expression must have the same type as the method.  transfer the control flow back to the line of code that called this method. The expression next to the return keyword must be a String public String appVersion() { // Send back the current version of the program return "This is version 3.1"; }

CSC 142 C 26 Instance method: borrowBook (1)  Input: title of the book to borrow  Output: did the operation succeed? (only one book can be borrowed). Return a boolean (true if success, false if failure).  Code (inside the LibraryMember class) public boolean borrowBook(String someTitle) { // What do we write?...  Can the LibraryMember borrow a Book?  Yes, if book is null. No, if book is not null.

CSC 142 C 27 Instance method: borrowBook (2)  Code (inside the LibraryMember class) public boolean borrowBook(String someTitle){ if (book==null) { // Can borrow the book book = new Book(someTitle); // Note the use of + to concatenate Strings System.out.println("Borrow " + someTitle); return true; } else { // Can't borrow the book // Note '\n' to print a new line System.out.println("You can't borrow "+ someTitle +"\nYou already have a book"); return false; } }

CSC 142 C 28 Putting it all together (1)  class diagrams: + for public, - for private LibraryMember - int ssn - Book book + LibraryMember(int) + boolean returnBook() + boolean borrowBook(String) Book - String title + Book(String)

CSC 142 C 29 Putting it all together (2) public class LibraryMember{ // id and borrowed book private int ssn; private Book book; // constructor public LibraryMember(int someSSN){ssn=someSSN;} // other methods (see previous slides) public boolean returnBook(){/*code*/} public boolean borrowBook(String someTitle) { // code }

CSC 142 C 30 Using the class LibraryMember public class UsingLibraryMember{ public void testLibraryMember() { // Borrow and return and see if it works LibraryMember lm=new LibraryMember( ); lm.borrowBook("The great Gatsby"); if (lm.returnBook()) System.out.println("It is working"); if (lm.borrowBook("The old man and the sea")) System.out.println("It is still working"); lm.borrowBook("Learning Java"); lm.returnBook(); lm.borrowBook("Learning Java"); }