February 11, 1999CSPP503 Week 6 Bring on the Caffeine CSPP503 Week 6.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Python Objects and Classes
Written by: Dr. JJ Shepherd
CS102 A Wide Array of Possibilities CS 102 Java’s Central Casting.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Access to Names Namespaces, Scopes, Access privileges.
Enhancing classes Visibility modifiers and encapsulation revisited
More on Objects CS 102 More, more, more on Objects.
CS102 Data Types in Java CS 102 Java’s Central Casting.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Review of C++ Programming Part II Sheng-Fang Huang.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Chapter 5- Even more about objects and methods. Overview n Designing methods n Methods, methods, methods n Overloading methods n Constructor methods n.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
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.
CSE 131 Computer Science 1 Module 1: (basics of Java)
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
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.
Introduction to java Prepared By:-Pragnesh Patel Lect. In Computer Dept. NSIT,Jetalpur 1.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 6- Arrays. Overview n What are arrays? n Declaring/initializing arrays. n Using arrays. n Arrays details. n Using arrays with classes/ in classes.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Chapter 5 Introduction to Defining Classes
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
OOP Basics Classes & Methods (c) IDMS/SQL News
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Arrays Chapter 7.
Information and Computer Sciences University of Hawaii, Manoa
Topic: Classes and Objects
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Programming Language Concepts (CIS 635)
A Wide Array of Possibilities
Java Programming Language
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Java’s Central Casting
Names of variables, functions, classes
Presentation transcript:

February 11, 1999CSPP503 Week 6 Bring on the Caffeine CSPP503 Week 6

February 11, 1999CSPP503 Week 6 Are You Java’s Type? Type: a set of values that are semantically similar Java is a strongly typed language – Every variable and every expression has a type that is known at compile time. – Strong typing helps detect errors at compile time.

February 11, 1999CSPP503 Week 6 Inside a Primitive Type Actual values for integral types: byte: -128 to 127 short: to int: to long: to char: from '\u0000' to '\uffff’ (from 0 to 65535) Why use int instead of long ?

February 11, 1999CSPP503 Week 6 Building a Boolean from a Number Can’t say (why not?): if (x) System.out.println(“Congratulations, it’s a Boole!”); Convert an integer x (following the C language convention that any nonzero value is true): if (x != 0) System.out.println(“Congratulations, it’s a Boole!”);

February 11, 1999CSPP503 Week 6 Building a Boolean from an Object Object reference obj can be converted (any reference other than null is true): obj! = null

February 11, 1999CSPP503 Week 6 The Other Kind of Type Reference types – Variables of reference types don’t hold values, but references to values – Classes, interfaces and arrays are all reference types

February 11, 1999CSPP503 Week 6 A Graphical View int counter Airport midway The data of the midway object

February 11, 1999CSPP503 Week 6 Classes, Interfaces and Arrays, oh my! Classes we’ve already seen Interfaces are programming contracts – An interface is a set of constants and methods – In Java, a class implements an interface

February 11, 1999CSPP503 Week 6 Implementing an Interface An example from the Comparison applet: public class Comparison extends Applet implements ActionListener Comparison promises to do everything an ActionListener does

February 11, 1999CSPP503 Week 6 Comparison Does What It Has To What does an ActionListener have to do? actionPerformed public abstract void actionPerformed(ActionEvent e) Provides an implementation for the interface: public void actionPerformed(ActionEvent e) { number1 = Integer.parseInt(input1.getText() ); number2 = Integer.parseInt(input2.getText() ); repaint(); }

February 11, 1999CSPP503 Week 6 Comparison Object has Two Types Comparison is a class that implements an interface: public class Comparison extends Applet implements ActionListener

February 11, 1999CSPP503 Week 6 Interface Type Example From the Comparison applet: input2 = new TextField( 10 ); input2.addActionListener( this ); add( input2 ); // put input2 on applet What is addActionListener()? public synchronized void addActionListener(ActionListener l)

February 11, 1999CSPP503 Week 6 Sideline Events Events are things that happen to programs (other than errors) // Process user's action on the input2 // text field public void actionPerformed(ActionEvent e) { number1 = Integer.parseInt( input1.getText() ); number2 = Integer.parseInt( input2.getText() ); repaint(); }

February 11, 1999CSPP503 Week 6 Class ? Type Variables have types Objects (and arrays) don’t have a type, but belong to a class Usually we’ll consider them the same

February 11, 1999CSPP503 Week 6 Casting Against Type A value could be two different types – Is 12 an int or a float? Compiler isn’t smart, so it’s conservative (signals an error) Override the compiler with a cast – Cast says: Treat this variable as the type I say – To cast in Java, write: (newType) variable

February 11, 1999CSPP503 Week 6 Examples of casting // Casting a float literal to a type int. // Without the cast operator, this would be a // compile-time error, because it’s a narrowing // conversion: int i = (int)12.5f; // From class average applet (Figure 2.9) if ( counter != 0 ) { average = (double) total / counter; System.out.println( "Class average is " + average ); } else...

February 11, 1999CSPP503 Week 6 Can’t Always Cast Can’t do this: if ((boolean) x) System.out.println(“Congratulations, it’s a Boole!”); Sometimes casts are automatic, and are called conversions

February 11, 1999CSPP503 Week 6 One of Two Ways Create an expression in a context where the type of the expression is not appropriate and either: – Error at compile time ( if statement has any type other than boolean ) – May be able to accept a type that is related to the type of the expression

February 11, 1999CSPP503 Week 6 Funky Conversions What does this print? class Test { public static void main(String[] args) { int big = ; float approx = big; System.out.println(big -(int)approx); }

February 11, 1999CSPP503 Week 6 What’s an Array An array is a group of values of the same type (usually stored in consecutive memory locations) Arrays are objects – Can be assigned to variables of type Object Dynamically created

February 11, 1999CSPP503 Week 6 An Array of Examples From Figure 5.3 int n[]; // declare an array of integers // initialize instance variables public void init() { n = new int[ 10 ]; //dynamic allocation }

February 11, 1999CSPP503 Week 6 The Declaration of Array Array declarations int[] ai; // array of int short[][] as;// array of array of short Object[] ao, // array of Object otherAo; // array of Object

February 11, 1999CSPP503 Week 6 Declaring Arrays Can’t specify the length in a declaration int test [] = new int [100]; // Okay int test2 [100]; // No good int test3 [100]=new int [100]; // No good

February 11, 1999CSPP503 Week 6 Some Array Definitions These create array objects: Exception ae[] = new Exception[3]; Object aao[][] = new Exception[2][3]; int[] factorial = { 1, 1, 2, 6, 24 }; String[] aas = {"array", "of", "String"};

February 11, 1999CSPP503 Week 6 An Array Example int face; int frequency[]; // initialize instance variables public void init() { frequency = new int[ 7 ]; for (int roll=1; roll <= 6000; roll++ ) { face = 1 + (int) (Math.random() * 6 ); ++frequency[ face ]; }

February 11, 1999CSPP503 Week 6 An Array of Observations Arrays know their own length test.length == 100 – What kind of loops do we usually use with arrays? Arrays start at index 0 – Last index == ?? Arrays must be indexed by int values ( short, byte, or char are okay, but long is no good)

February 11, 1999CSPP503 Week 6 Operating on an Array Square brackets are an operator Brackets have very high precedence – Same as ()’s Example -17*studentGrades[12] * 2

February 11, 1999CSPP503 Week 6 "Can he do that?" What’s wrong with the following code? int scores[] = {98, 76, 84, 97, 101, 78}; int counter=0; for (; counter <= scores.length; counter++) { System.out.println("Test #" + counter + ": " + scores[counter]); }

February 11, 1999CSPP503 Week 6 Array Initializers Use {}’s to set initial values – int grades[] = {87, 92, 76, 94}

February 11, 1999CSPP503 Week 6 Searching & Sorting Data The Second Law of Thermodynamics Sorting restores order to the world Sorting in everyday life – Bank checks by account Searching is easier when sorted – Reverse directories of phone numbers

February 11, 1999CSPP503 Week 6 Sorting in Computers Usually start with an array of items to be sorted – Integers – Social Security numbers – Last names and first names Lots of data – All the SSN’s in the U.S. – All of GM’s employees

February 11, 1999CSPP503 Week 6 Different Ways to Sort Bubble sort – Compare two neighbors, swap if out of order

February 11, 1999CSPP503 Week 6 The Code for Bubble Sort public void sort() { int hold; // temporary holding area for swap // passes for ( int pass = 1; pass < a.length; pass++ ) // one pass for ( int i = 0; i < a.length - 1; i++ ) // one comparison if ( a[ i ] > a[ i + 1 ] ) { // one swap hold = a[i]; a[ i ] = a[ i + 1 ]; a[ i + 1 ] = hold; } Nested for loops

February 11, 1999CSPP503 Week 6 There’s More Than One Way to Sort a Cat Other sorts – Quicksort – Heapsort – Bucket sort Different sorts have different characteristics – Memory usage – Speed

February 11, 1999CSPP503 Week 6 Searching Here, There & Everywhere Need to find a value? Search for it! Linear search – Is it the next one? No, then look again Yes, stick a fork in me, ‘cuz I’m done – Works on unsorted items Binary search – Cut in half every time

February 11, 1999CSPP503 Week 6 Arrays of Arrays Arrays in multiple dimensions – Not just a list – A table (an array of arrays) – A cube (an array of arrays of arrays)

February 11, 1999CSPP503 Week 6 An Example An array of arrays int b[][] = { {1,2}, {3, 4, 5}} Row 0:12 Row 1:345 A 3x3 array int b[][]; b = new int[3][3];

February 11, 1999CSPP503 Week 6 Where Do You Want To Go Today? Building new objects Accessors this and That

February 11, 1999CSPP503 Week 6 Caution, Objects Under Construction! Objects have structure and structure has to be built new means create a new instance of an object How are objects actually built? – Objects know how to do things, including how to build themselves

February 11, 1999CSPP503 Week 6 Constructor Methods Constructors are special methods that build new objects – Declaration looks just like a method declaration that has no result type public class Circle { double x_center, y_center, radius; public Circle(double x, double y, double r) { x_center = x; y_center = y; radius = r; }

February 11, 1999CSPP503 Week 6 A Few Notes on Constructors I Don't have to declare a constructor – Java creates a default constructor public class Circle { public double x_center, y_center, radius; // Uses the default constructor public double Area() { return d * radius * radius; }

February 11, 1999CSPP503 Week 6 A Few Notes on Constructors II Constructors have the same name as the class No return type (why not?) Constructor declarations are not members – Never inherited, so no hiding or overriding (More on this later)

February 11, 1999CSPP503 Week 6 Multiple Constructors public Circle(double x, double y, double r) { x_center = x; y_center = y; radius = r; } public Circle() { x_center = 0; y_center = 0; radius = 1; } public Circle(double x, double y) { x_center = x; y_center = y; radius = 1; }

February 11, 1999CSPP503 Week 6 Handling Multiple Constructors How does Java tell the constructors apart? – Method signatures – Signatures include: Name of the method Number formal parameters Types of formal parameters – Doesn't include the name of the parameter

February 11, 1999CSPP503 Week 6 Method Signatures For this method: public Circle(double x, double y, double r) Signature is: Circle(double, double, double) Different methods, same signature public Circle(double x, double y) public Circle(double x, double r)

February 11, 1999CSPP503 Week 6 Back to Multiple Constructors Multiple constructors are okay – Each constructor has to have a unique signature (All of a class's methods have to have unique signatures, not just constructors) Method overloading: multiple versions of the same method (but with different signatures)

February 11, 1999CSPP503 Week 6 The Linda Tripp Problem How do we keep private data private? Avoid having object1 mess with object2 's data Example: Student objects know student's grades, but one student shouldn't modify another student's grades. Storing invalid data – Stuffing 12-hr time into a 24-hr time object

February 11, 1999CSPP503 Week 6 If It's Public... Start with: public class Circle { public double x_center, y_center; public double radius, area; public Circle(double x, double y) { x_center = x; y_center = y; radius = 1; area = }

February 11, 1999CSPP503 Week 6 …other objects can mess with it Create a circle Circle duPont = new Circle(100d, 100d); // Change the area, but leave r the same duPont.Area = 11; // Now a circle with radius 1 has area 11

February 11, 1999CSPP503 Week 6 Using private Declare variables to be private public class Circle { private double x_center, y_center; private double radius, area; : } Now only Circle can modify the variables (x_center, y_center,...)

February 11, 1999CSPP503 Week 6 Granting Access Other classes might need to read or write the values stored in private members Create accessor functions – Set (or settor) – Get (or gettor) Control access through get and set

February 11, 1999CSPP503 Week 6 Setting and Getting What's the difference between using get and set methods, and just making everything public ? Two benefits – Protect instance variables from outside meddling – Insulates class users from changes in variables

February 11, 1999CSPP503 Week 6 Example from Fig 6.5 // blah, blah, blah. Set invalid values to zero. public void setTime( int h, int m, int s ) { setHour( h ); // set the hour setMinute( m ); // set the minute setSecond( s ); // set the second } // set the hour public void setHour( int h ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); } // set the minute public void setMinute( int m ) { minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); } // set the second public void setSecond( int s ) { second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

February 11, 1999CSPP503 Week 6 Me, a Name I Call Myself How can objects refer to themselves? – Every object has a built-in reference to itself, called this this can be used only in: – Body of a method or constructor – Initializer of an instance variable – Anywhere else is a compile-time error

February 11, 1999CSPP503 Week 6 This is Bad, public class Circle { public double x, y; public double r, area; public Circle(double x, double y) { x = x;// This doesn't do much, because we're y = y; // just assigning parameters to themselves r = 1; area = }

February 11, 1999CSPP503 Week 6 But this is okay public class Circle { public double x, y; public double r, area; public Circle(double x, double y) { this.x = x;// Now we're assigning the instance this.y = y; // variables to the parameters r = 1; area = } Better to avoid this mess altogether by using different names for data members and method parameters