Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Written by: Dr. JJ Shepherd
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
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.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Games and Simulations O-O Programming in Java The Walker School
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS 106 Introduction to Computer Science I 03 / 19 / 2007 Instructor: Michael Eckmann.
A way to pull together related data A Shape Class would contain the following data: x, y, height, width Then associate methods with that data A Shape.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
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.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
From C++ to Java A whirlwind tour of Java for C++ programmers.
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.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
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 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS 106 Introduction to Computer Science I 10 / 29 / 2007 Instructor: Michael Eckmann.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
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.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Intro To Classes Review
CS 302 Week 11 Jim Williams, PhD.
Encapsulation and Constructors
Today’s topics UML Diagramming review of terms
CS100J Lecture 8 Previous Lecture This Lecture Programming Concepts
Java Programming Language
Special instance methods: toString
Review for Midterm 3.
Chapter 7 Objects and Classes
Presentation transcript:

Questions? Suggestions?

References

References Revisited What happens when we say: int x; double y; char c; ???

We create variables xycxyc Variable: Symbol plus a value

Assume that we have class Box class LLNode as well as the usual suspects: class String, etc.

What happens when we say Box b; LLNode head; String s;

We create variables b head s Reference variables hold the location of objects. If they aren't referencing an object what is their value? Reference variables hold the location of objects. If they aren't referencing an object what is their value? Java keeps track of what type of object each reference can "point" to. Java keeps track of what type of object each reference can "point" to. Box LLNode String

Common Errors! Box b = new Box(1, 2, 3);. Box b = new Box(4, 5, 6);.

Should be: Box b = new Box(1, 2, 3);. b = new Box(4, 5, 6);.

Common Errors! Box b = new Box(1, 2, 3); b = anotherBox;

Should be: Box b; b = anotherBox;

Common Errors! class Whatever { Box b; // Constructor public Whatever() { Box b = new Box(1, 2, 3);

Should be: class Whatever { Box b; // Constructor public Whatever() { b = new Box(1, 2, 3);

Understanding References Key to understanding –Arrays of Objects –Testing for Equality of Objects –Passing Objects to Methods –Assignment vs. Clone –etc. For example...

Now, let’s consider WHY... Understanding Equality The key to understanding equality comes from knowing how Java handles references and primitives. First, here’s the rule: When comparing primitives, use ==, thus: if ( iCount == iMaximum ) // etc. When comparing objects, use.equals(), thus: if ( box1.equals(box2) ) // etc.

Equality with Primitives: int x; int y; x = 11; y = 3; System.out.println(x == 11);// prints true System.out.println(y = = 3);// prints true System.out.println(x = = y);// prints false x = y; System.out.println(x = = 3);// prints true System.out.println(y = = 3);// prints true System.out.println(x == y);// prints true System.out.println(x > y);// prints false Testing Equality: Primitives 11 x: 3 y: 3 x: 3 y:

1. Are the references equal? Test with == In other words, are both references pointing to exactly the same object? Considered to be the most stringent test for equality Testing Equality: Objects

2. Are the objects themselves equal? The answer depends on your definition of equality! Create an equals() method which compares the internal state of the object with another object passed in as a reference. You need to create this method for every class where you will need to compare objects for equality Testing Equality: Objects

Example class Rectangle { int len, wid; String name; // Constructor and basic get/set methods not shown public boolean equals(Object o) { boolean retVal = false; if(o instanceOf Rectangle) { Rectangle r = (Rectangle)o; if(r.getLen() == len && r.getWid() == wid) retVal = true; } return retVal; }

Example public static void main(String args[]) { Rectangle r1 = new Rectangle(3,4,"Bob"); Rectangle r2 = new Rectangle(3,4,"Ted"); Rectangle r3 = new Rectangle(8,7,"Bob"); Rectangle r4 = r1; String s = "Goofy"; System.out.println(r1.equals(r2)); System.out.println(r1.equals(r3)); System.out.println(r1.equals(r4)); System.out.println(r1.equals(s)); } } // Rectangle

Recall the LLNode public boolean equals(Object o) { boolean retVal = false; if(o instanceOf LLNode) { retVal=getData().equals(((LLNode)o).getData()); } return retval; } Holy OO Gobbledy-Gook Batman!!!! data next data next ??

The LLNode public static void main(String args[]) { LLNode n4 = new LLNode("delta", null); LLNode n3 = new LLNode("gamma", n4); LLNode n2 = new LLNode("beta", n3); LLNode n1 = new LLNode("alpha", n2); LLNode tester = new Node("beta", null); System.out.println(n1.equals(tester)); System.out.println(n2.equals(tester)); System.out.println(n3.equals(tester)); System.out.println(n4.equals(tester)); }

Note! The.equals() method in class Object is simply ==

Scope

Scope Local variables (declared as a part of method): Can be seen only from within their method. Outside of their method, their identifiers have no meaning. Instance and Class variables (declared as part of a class, but not within a particular method): Can be seen from anywhere in the instance. This means they can be seen from within methods defined within the class without passing them to the method as parameters. May or may not be visible beyond (soon). Within a method, local variable identifiers take precedence over instance variable IDers

What we want: class Person { String strName;... public void setName (String strName) { strName = strName; } // of setName Inside the method, the String strName refers to the String in the method signature. This creates a problem: which strName is which? Preventing Identifier Ambiguity WRONG!

What we get: class Person { String strName;... public void setName (String strName) { strName = strName; } // of setName Inside the method, the String strName refers to the String in the method signature. This creates a problem: which strName is which? Preventing Identifier Ambiguity WRONG!

Solutions: Rename the formal parameter: public void setName (String strNewStringName) { strName = strNewStringName; } // of setName Use the keyword this to refer to “current object” public void setName (String strName) { this.strName = strName; } // of setName Preventing Identifier Ambiguity Preferred with Javadocs

Shadowing

Shadowing Refers to "hiding" something that still exists Simple case today Will come back to this topic during discussion on inheritance

Shadowing class Widget { name public String name; public void someMethod(int i) { name String name; /* Shadows instance variable */ name name = "Bob"; this.name this.name = "Wally"; /* Accessing the shadowed variable! */

Chaining

Some Constructors class Rectangle { private int length, width; private String name; public Rectangle () { setLength(0); setWidth(0); setName("Unnamed"); } // constructor public Rectangle (int l, int w) { setLength(l); setWidth(w); setName("Unnamed"); } // constructor public Rectangle (int l, int w, String n){ setLength(l); setWidth(w); setname(n); } // constructor

Constructor "Chaining" class Rectangle { private int length, width; private String name; public Rectangle () { this(0,0,"Unnamed"); } // constructor public Rectangle (int l, int w) { this(l, w,"Unnamed"); } // constructor public Rectangle (int l, int w, String n){ setLength(l); setWidth(w); setname(n); } // constructor

Add a count? class Rectangle { private int length, width; private String name; private static count = 0; public Rectangle () { setLength(0); setWidth(0); setName("Unnamed"); count++; } // constructor public Rectangle (int l, int w) { setLength(l); setWidth(w); setName("Unnamed"); count++; } // constructor public Rectangle (int l, int w, String n){ setLength(l); setWidth(w); setname(n); count++; } // constructor

Add a count, simpler with "Chaining" class Rectangle { private int length, width; private String name; private static int count = 0; public Rectangle () { this(0,0,"Unnamed"); } // constructor public Rectangle (int l, int w) { this(l, w,"Unnamed"); } // constructor public Rectangle (int l, int w, String n){ setLength(l); setWidth(w); setname(n); count++; } // constructor

Arrays

Arrays An array may be declared to be: – an array of primitives, or – an array of objects (actually references!!!). The Array itself is an Object, even if the array contains primitives. –(Array identifier references an object). If an array of objects, then: – the array identifier is a reference to the array object – each array element is a reference to an object of the class specified as elements Instantiating the array object does not instantiate the various element objects to which it refers. Element objects must be explicitly instantiated and initialized.

Example: Imagine a Flatware object which keeps track of: knives, forks and spoons. class Flatware { int knives = 0; int forks = 0; int spoons = 0; public Flatware(int knives, int forks, int spoons) { setKnives(knives); setForks(forks); setSpoons(spoons); } // of constructor /* We assume accessors, modifiers--getKnives(), setKnives(), etc. -- are implemented here */ } // of Flatware Arrays

Then, the code segment: Flatware fw1 = new Flatware(10, 20, 30); Flatware fw2; produces: knives = 10 forks = 20 spoons = 30 fw1 fw2 Arrays

and the code segment: Flatware[ ] flatwareArray = new Flatware[5]; produces: which could then be initialized via: int i; for ( i = 0; i < flatwareArray.length; i++) { flatwareArray[i] = new Flatware(10, 20, 30); } // of for loop initialization flatwareArray Arrays

giving: flatwareArray knives = 10 forks = 20 spoons = 30 fw1 fw2 7 objects in total 6 Flatware objects Arrays knives = 10 forks = 20 spoons = 30 knives = 10 forks = 20 spoons = 30 knives = 10 forks = 20 spoons = 30 knives = 10 forks = 20 spoons = 30 knives = 10 forks = 20 spoons = 30

but the code segment: int i; for ( i = 0; i < flatwareArray.length; i++) { flatwareArray[i] = fw1; } // of for loop initialization produces: flatwareArray fw1 1 Flatware object... 2 objects in total Arrays knives = 10 forks = 20 spoons = 30

Review: Array Creation Declaration int myInts[]; int[] myInts; Instantiation myInts = new int[10]; Declaration and instantiation: int[] myInts = new int[10]; Access to individual element myInts[3] = 9; x = myInts[4]; Static initialization int[] myInts = {1,2,5,6,7,4};

Multi-Dimensional Arrays int[][] myTwoDimArray; myTwoDimArray = new int[10][5]; Quiz Yourself! Valid? String[][] s; s = new String[10][]; Valid? s = new String[][10]; //YES! // NO!

String s[][] = {{"Static", "multidimensional", "initialization", "of"}, {"arrays", "requires", "the", "use"}, {"of", "nested", "curlies"} }; Creates: Static multidimensional initialization: Static arrays of multidimensional requires nested Initialization the curlies of use (null)

Summary of Arrays Arrays All arrays are objects (you have to declare, instantiate, and initialize) Arrays are either arrays of primitive elements (e.g. int) or arrays of objects (really references to objects) Arrays are statically sized: you can’t change length after declaration; arrays know their own length –Use Array.length in for loops to avoid “off-by-one” errors 2D arrays are arrays of arrays

Questions?