CSC 142 Computer Science II Zhen Jiang West Chester University

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

1 Value vs. reference semantics. Recall: Value semantics value semantics: Behavior where variables are copied when assigned to each other or passed as.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Road Map Introduction to object oriented programming. Classes
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
Java Syntax Primitive data types Operators Control statements.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
Computer Science 1620 C++ - Basics. #include using namespace std; int main() { return 0; } A very basic C++ Program. When writing your first programs,
Java Unit 9: Arrays Declaring and Processing Arrays.
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
Input & Output: Console
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
Primitive Variables.
Property of Jack Wilson, Cerritos College1 CIS Computer Programming Logic Programming Concepts Overview prepared by Jack Wilson Cerritos College.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 CIS 2168 Data Structures and Algorithms in JAVA Brief Introduction to JAVA.
Objects.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
CSC 142 Computer Science II Zhen Jiang West Chester University
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
CSC 142 F 1 CSC 142 References and Primitives. CSC 142 F 2 Review: references and primitives  Reference: the name of an object. The type of the object.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
CPSC 233 Tutorial 5 February 9 th /10 th, Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
Object - CIS 1068 Program Design and Abstraction
Objects as a programming concept
Chapter 8 Arrays, Strings and Pointers
“Interview coding is not the same skill as coding in real life where you have Stack Overflow, reference materials, and an editor. ”
Java Primer 1: Types, Classes and Operators
Documentation Need to have documentation in all programs
Object Oriented Programming
Java Review: Reference Types
Java Programming: From Problem Analysis to Program Design, 4e
Instance Method Review - CIS 1068 Program Design and Abstraction
CSC240 Computer Science III
CSC240 Computer Science III
Building Java Programs Chapter 2
Computers & Programming Languages
Variables ICS2O.
CSC240 Computer Science III
Building Java Programs
Building Java Programs
Instance Method – CSC142 Computer Science II
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
Chapter 3 Introduction to Classes, Objects Methods and Strings
Presentation transcript:

CSC 142 Computer Science II Zhen Jiang West Chester University

Table of Contents Introduction to object Class and object Representing objects Calling methods Fields Remarks Value vs. reference Summary 22/6/2016

3 Objects data type: A category of data values.  Example: integer, real number, string Java data types are divided into two sets:  primitive types: Java's 8 built-in simple data types for numbers, text characters, and logic. boolean, char, byte, short, int, long, float, double  object types: All other types! e.g., Scanner, System, String, Math

4 object: An variable that contains data and behavior. There are variables inside the object, representing its data. There are methods inside the object, representing its behavior. class: Basic building block of Java programs (what we have seen so far)‏ AND Types for objects

5 Theoretical examples: A class Person could represent objects that store a name, height, weight, hair color, IQ, etc… and those values’ change A class Laptop could represent objects that store speed, screen size, color, dimensions, brand, etc… and the variety of status’ change Examples from Java: The class String represents objects that store text characters. The class Scanner represents objects that can tokenize streams of characters.

6 Class and objects ( Dog ) Source directory How to run multi-class program Current project

Data stored in each Dog object: Useful methods/behaviors in each Dog object: 7 Field, attribute, data name breed age Method, behavior, function, status change Description writeOutput ( )Display data status getAgeInHumanYears ( )Calculate with current status

8 construct: To create a new object. Objects are constructed with the new keyword. Constructing objects, general syntax: = new ( ); Examples: Dog scooby = new Dog( ); Scanner console = new Scanner(System.in); Q: Wait a minute! Why don’t we construct strings with new ? A1: Strings are one of the most commonly used objects, so they have special syntax (quotation marks) to simplify their construction. A2: Also, you can if you want to: String s = new String(“hi”);

So far, I have drawn primitive types like this: int x = 7; 7 X:

Representing objects I will represent object types like this: Dog balto = new Dog(); Balto.name = “Balto”; balto: “Balto” ? name:breed: Variable, with slot in memory Reference, a pointer to the object’s data Data, in another part of memory Fields ? age:

Object variables are references to the location in memory where their data resides. We draw references as pointers. Actually, balto stores the address of the location in memory where its data is. balto: “Balto” ? name:breed: Variable, with slot in memory Reference, a pointer to the object’s data Data, in another part of memory Fields ? age:

null is a value for all object types that says, “this object is a reference to nothing at all” We draw null objects with a slash Note that null objects have no memory reserved for their data! Dog p1 = null; 12 p1:

13 Calling methods on objects Since the methods are bundled in the objects, calling these methods requires specifying which object we are talking to. Calling a method of an object, general syntax:. ( )‏ The results may vary from one object to another. Examples: String s1 = “Homey da Clown”; String s2 = “Bubbles the clown”; System.out.println(s1.length());// prints 14 System.out.println(s2.length());// prints 17 int humanYears = scooby.getAgeInHumanYears ( );

When we use the “.” operator on an object, we access the stuff (methods and/or data) that the object references (or points to). This is called dereferencing. The “.” operator is the dereferencing operator.

We have seen three ways to call methods: Type:No ‘.’ used. When it’s used:For methods defined in the same class as they’re called For static methods defined in another class For non-static or instance methods defined in another class Examples:myMethod();Math.max(a,b)myString.length() Integer.parseInt(“6”)console.nextInt() Server.gcd(15,12)myPoint.translate(2,2)

Fields Fields are variables that contain data for an object. Since the fields are bundled in the objects, referring to fields requires specifying an object. Referring to the field of an object, general syntax:. Examples: scooby.name = “Scooby”; Scooby.age = 42; // displays dog’s age System.out.println(“He is“ + scooby.age + “ years old, or “);

Remarks The dreaded NullPointerException Point p = null; p.x = 7; // Error! p.setLocation(0,0);// Error! If you try to dereference a null object, it will cause a NullPointerException. Why? This is a very common error, but one nice thing about Java is that it is often fairly easy to fix this kind of error (in my experience).

Concept: An object is an instance of its class. Each instance has its own local copy of the state and behavior defined in the class template. Example: each Dog object has its own name, and its own getAgeInHumanYears method.

19 Dog class state: String name, breed int age behavior: writeOutput ( ) getAgeInHumanYears ( )‏ Point object balto state: “Balto” (name) 8 (age) “Siberian Husky” (breed) behavior: getAgeInHumanYears ( ) writeOutput ( ) Point object scooby state: “Balto” (name) 8 (age) “Siberian Husky” (breed) behavior: getAgeInHumanYears ( ) writeOutput ( )

Value vs. Reference value semantics: Behavior where variables are copied when assigned to each other or passed as parameters. Primitive types in Java use value semantics. Modifying the value of one variable does not affect other. Example: int x = 5; int y = x; // x = 5, y = 5 y = 17; // x = 5, y = 17 x = 8; // x = 8, y = 17 20

reference semantics: Behavior where variables refer to a common value when assigned to each other or passed as parameters, p Object types in Java use reference semantics. Object variables do not store an object; they store the address of an object's location in the computer memory. We graphically represent addresses as arrows. Example: Dog balto = new Dog ( ); balto.name = “Balto”; balto.age = 8; balto.breed = “Siberian Husky”; 21 Balto balto Siberian Husky8

If two object variables are assigned the same object, the object is NOT copied; instead, the object’s address is copied. As a result, both variables will point to the same object. Calling a method on either variable will modify the same object. Example: Dog balto = new Dog(); Dog myDog = balto; 22 Balto balto Siberian Husky8 myDog

Objects have reference semantics for several reasons: efficiency: Objects can be large and bulky. Having to copy them every time they are passed as parameters would slow down the program. sharing: Since objects hold important state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object. 23

Objects store references, or addresses. Comparing two objects with == will test if they have the same address. This is NOT what you want. DO NOT DO THIS Dog balto = …; Dog scooby = …; if(balto == scooby) { … } BAD

Dog scooby = new Dog ( ); Dog mydog = new Dog ( ); Is mydog == scooby true or false? It’s false: they point to different spots in memory. So they store different addresses. But we want it to be true, obviously!

All classes in Java have a built-in equals method, p513 For the Dog class: mydog.equals(scooby) This returns true if mydog and scooby have the same data It doesn’t matter if they reference different locations in memory Likewise, use !mydog.equals(scooby) instead of mydog != scooby

Summary Object typesPrimitive types Constructed with the new keywordValues don’t need to be constructed References to memory location that stores their data Store data directly in memory slot Can be null (have no data)Cannot be null Can cause NullPointerExceptionsCannot cause NullPointerExceptions Contain state and behaviorContain state only Use reference semanticsUse value semantics Use equals() methodUse ==, !=

Class & object, UML representation, p331 Multiple file project and NetBeans Representing object Sample program to explain the declaration (construction), method call, (attribute) field, and reference of object (value change and comparison, p509), Dog.java & DogDemo.java 282/6/2016