cs 340 data structures lecture: everything is an object
TRANSCRIPT
CS 340 DATA STRUCTURESLecture: Everything is an Object
CS 340 2
OOP or… Object Oriented Programming
CS 340 3
Object-Oriented Languages• Smalltalk, C++, Java, etc…• You can make any kind of objects you want• How different from procedural languages?
• No different at all: Every (reasonable) language is “Turing complete”
• Very different: Make expression easier, less error-prone
CS 340 4
O-O Languages (Alan Kay)• Everything is an object. • A program is a bunch of objects telling each other what to
do, by sending messages. • Each object has its own memory, and is made up of other
objects. • Every object has a type (class). • All objects of the same type can receive the same
messages.
CS 340 5
Objects• An object has an interface, determined by its class.• A class is an abstract data type, or user-defined type.• Designing a class means defining its interface.
CS 340 6
Built-In Types• Think of an int…
• What is its interface?• How do you “send it messages”?• How do you make one?• Where does it go when you’re done with it?
• In solving a computational problem, the goal is to• Invent useful classes, and• Give them appropriate characteristics.
CS 340 7
Example• Suppose I’ve defined this class in Java:
• To make one, I typeBottleOfBeer myBeer = new BottleOfBeer();
• If I want myBeer opened, I saymyBeer.open();
BottleOfBeer
+open():void+lift(height:int):void+tilt(angle:int):void
CS 340 8
But Why Not Just…
• This is legal, but just makes a “reference variable” named myBeer
• This variable can refer to any BottleOfBeer object, but currently refers to nothing
• The operator new actually causes an object to be created, so we tell it what kind we want
BottleOfBeer myBeer;
CS 340 9
Designers Design, Users Use
• The interface is the critical part, but the details (implementation) are important too.
• Users use the interface (the “public part”); the implementation is hidden by “access control”.
BottleOfBeer
-topOn:Boolean
+open():void+lift(height:int):void+tilt(angle:int):void
CS 340 10
Two Ways of Reusing Classes• Composition: One class has another as a part (indicated
by the diamond “aggregation” symbol).
BottleOfBeer
+open():void+lift(height:int):void+tilt(angle:int):void
TavernCaseOfBeer
Patron
CS 340 11
Two Ways of Reusing Classes• Inheritance: One class is a specialized version of another
(indicated by the triangle “inheritance” symbol).
BottleOfBeer
+open():void+lift(height:int):void+tilt(angle:int):void
BottleOfRollingRock
-lowCalorie:Boolean
+isLowCalorie():Boolean
CS 340 12
Polymorphism• Different subclasses respond to the same message,
possibly with different actions.
Patron
+beerPlease():Polite
BritishPatronAmericanPatron
+beerPlease():Rude
GermanPatron
+beerPlease():InGerman
CS 340 13
Some Java CodePatron p1 = new Patron(); Patron p2 = new YankPatron(); Patron p3 = new BritPatron();
Patron p4 = new GermanPatron(); p1.BeerPlease() // polite request p2. BeerPlease() // rude request p3.BeerPlease() // polite request
p4.BeerPlease() // request in German (but polite)
• This is a bit of a trick: it requires late binding of the function call.
CS 340 14
QUESTIONS?
CS 340 15
Creating Objects• We usually assume this is free; with built-in types like int
or char, we just say
int i; char c;
• With user-defined types (the ones we make), we need to be explicit about what we want: • constructor function
• This is a very important issue!
CS 340 16
Destroying Objects• If an object goes “out of scope,” it can no longer be used
(its name is no longer known).• Java uses references and “garbage collection”.
CS 340 17
Example of Object Scope
• What happens to lect?• The LectureNotes object still exists, but the reference lect disappears (it’s out of scope after return).
• Eventually, the garbage collector removes the actual LectureNotes object.
public String getTitle(int lectureNumber) { LectureNotes lect; lect = syllabus.getLecture(lectureNumber); String s = lect.getLine(1); return s;}
CS 340 18
Java’s Use of Memory• Stack• Heap• Static variables• Constants• Non-RAM storage
CS 340 19
Java’s Primitive TypesType Size Wrapper type
boolean - Boolean
char 16-bit Character
byte 8-bit Byte
short 16-bit Short
int 32-bit Integer
long 64-bit Long
float 32-bit Float
double 64-bit Double
void - Void
CS 340 20
Wrapper Types• Variables of primitive types are “automatic”, i.e., they are
stored on the stack.• They are automatically deleted when they go out of
scope.• What if you want an object holding a primitive type?
Example:
char c = ‘x’;Character C = new Character(‘x’);
CS 340 21
Really Big Numbers
• BigInteger, BigDecimal• These are arbitrary precision, as big as they need to be.• You can’t use the usual operators (+-*/) since they are
objects. But there are methods (functions) to do these things.
CS 340 22
Creating New Types
class MyNewType {
// definition here
}• Now it’s legal to say
MyNewType m = new MyNewType();
CS 340 23
Class Members• Fields (a.k.a. member variables, data members)• Methods (a.k.a. member functions): they determine the
messages objects can receive• The method argument list specifies what information you pass into
the method
class MyClass { int a; YourClass b; float memberFunction(int x, float f) { return 0; }}
CS 340 24
Let’s Write Something// Our first program. File: HelloDate.java// Note that the file name is exactly the same// as the class name, including capitalization.import java.util.*;
public class HelloDate { public static void main(String[] args) { System.out.println(“Hello, it is ”); System.out.println(new Date()); }}
CS 340 25
QUESTIONS?
CS 340 26
Java design
CS 340 27
Java Design Goals• Simple, object oriented, and familiar• Robust and secure• Architecture neutral and portable• High performance• Interpreted, threaded, and dynamic
CS 340 28
Java abbreviations• JDK: Java Development Kit• JSDK: Java Servlet Development Kit• JVM: Java Virtual Machine• J2EE: Java Platform, Enterprise Edition. A widely used
platform for server programming.
CS 340 29
Java vs C#Program Structure
Operators
Choices
Loops
30
Java vs C#: Program StructureJava C#
package hello;
public class HelloWorld { public static void main(String[] args) { String name = "Java"; // See if an argument was passed from the command line if (args.length == 1) name = args[0];
System.out.println("Hello, " + name + "!"); } }
using System;
namespace Hello { public class HelloWorld { public static void Main(string[] args) { string name = "C#";
// See if an argument was passed from the command line if (args.Length == 1) name = args[0];
Console.WriteLine("Hello, " + name + "!"); } } }
31
Java vs C#: CommentsJava C#
// Single line/* Multiple line *//** Javadoc documentation comments */
// Single line/* Multiple line *//// XML comments on a single line /** XML comments on multiple lines */
32
Java vs C#: Data TypesJava C#
Primitive Types boolean byte char short, int, long float, double
Reference Types Object (superclass of all other classes) Stringarrays, classes, interfaces
Value Types bool byte, sbyte char short, ushort, int, uint, long, ulong float, double, decimalstructures, enumerations
Reference Types object (superclass of all other classes) stringarrays, classes, interfaces, delegates
33
Java vs C#: Data TypesJava C#
Conversions
// int to String int x = 123; String y = Integer.toString(x); // y is "123"
// String to int y = "456"; x = Integer.parseInt(y); // x is 456
// double to int double z = 3.5; x = (int) z; // x is 3 (truncates decimal)
Conversions
// int to string int x = 123; String y = x.ToString(); // y is "123"
// string to int y = "456"; x = int.Parse(y); // or x = Convert.ToInt32(y);
// double to int double z = 3.5; x = (int) z; // x is 3 (truncates decimal)
34
Java vs C#: ConstantsJava C#
// May be initialized in a constructor final double PI = 3.14;
const double PI = 3.14;
// Can be set to a const or a variable. //May be initialized in a constructor. readonly int MAX_HEIGHT = 9;
35
Java vs C#: OperatorsJava C#
Comparison == < > <= >= !=
Arithmetic + - * / % (mod) / (integer division if both operands are ints) Math.Pow(x, y)
Assignment = += -= *= /= %= &= |= ^= <<= >>= >>>= ++ --
Bitwise & | ^ ~ << >> >>>
Comparison == < > <= >= !=
Arithmetic + - * / % (mod) / (integer division if both operands are ints) Math.Pow(x, y)
Assignment = += -= *= /= %= &= |= ^= <<= >>= ++ --
Bitwise & | ^ ~ << >>
36
Java vs C#: OperatorsJava C#
Logical && || & | ^ !
Note: && and || perform short-circuit logical evaluations
String Concatenation +
Logical && || & | ^ !
Note: && and || perform short-circuit logical evaluations
String Concatenation +
37
Java vs C#: ChoicesJava C#
greeting = age < 20 ? "What's up?" : "Hello";
if (x < y) System.out.println("greater");
if (x != 100) { x *= 5; y *= 2; } else z *= 6;
greeting = age < 20 ? "What's up?" : "Hello";
if (x < y) Console.WriteLine("greater");
if (x != 100) { x *= 5; y *= 2; } else z *= 6;
38
Java vs C#: ChoicesJava C#
int selection = 2;switch (selection) { // Must be byte, short, int, char, or enum case 1: x++; // Falls through to next case if no break case 2: y++; break; case 3: z++; break; default: other++; }
string color = "red";switch (color) { // Can be any predefined type case "red": r++; break; // break is mandatory; no fall-through case "blue": b++; break; case "green": g++; break; default: other++; break; // break necessary on default }
39
Java vs C#: LoopsJava C#
while (i < 10) i++;
for (i = 2; i <= 10; i += 2) System.out.println(i);
do i++; while (i < 10);
for (int i : numArray) // foreach construct sum += i;
while (i < 10) i++;
for (i = 2; i <= 10; i += 2) Console.WriteLine(i);
do i++; while (i < 10);
foreach (int i in numArray) sum += i;
40
Java vs C#: LoopsJava C#
// for loop can be used to iterate through any Collection import java.util.ArrayList; ArrayList<Object> list = new ArrayList<Object>();list.add(10); // boxing converts to instance of Integerlist.add("Bisons");list.add(2.3); // boxing converts to instance of Double
for (Object o : list) System.out.println(o);
// foreach can be used to iterate through any collection using System.Collections; ArrayList list = new ArrayList(); list.Add(10); list.Add("Bisons"); list.Add(2.3);
foreach (Object o in list) Console.WriteLine(o);
41
Java vs C#: ArraysJava C#
int nums[] = {1, 2, 3}; or int[] nums = {1, 2, 3};for (int i = 0; i < nums.length; i++) System.out.println(nums[i]);
String names[] = new String[5]; names[0] = "David";
float twoD[][] = new float[rows][cols]; twoD[2][0] = 4.5;
int[][] jagged = new int[3][]; jagged[0] = new int[5]; jagged[1] = new int[2]; jagged[2] = new int[3]; jagged[0][4] = 5;
int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++) Console.WriteLine(nums[i]);
string[] names = new string[5]; names[0] = "David";
float[,] twoD = new float[rows, cols]; twoD[2,0] = 4.5f;
int[][] jagged = new int[3][] { new int[5], new int[2], new int[3] };
jagged[0][4] = 5;
CS 340 42
QUESTIONS?