Everything is an Object

Download Report

Transcript Everything is an Object

CS 340 DATA
STRUCTURES
Lecture: Everything is an Object
CS 340
OOP or…
Object Oriented
Programming
2
CS 340
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
3
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
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.
6
CS 340
Example
• Suppose I’ve defined this class in Java:
BottleOfBeer
+open():void
+lift(height:int):void
+tilt(angle:int):void
• To make one, I type
BottleOfBeer myBeer = new BottleOfBeer();
• If I want myBeer opened, I say
myBeer.open();
7
CS 340
8
But Why Not Just…
BottleOfBeer myBeer;
• 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
CS 340
9
Designers Design, Users Use
• The interface is the critical part, but the details
(implementation) are important too.
BottleOfBeer
-topOn:Boolean
+open():void
+lift(height:int):void
+tilt(angle:int):void
• Users use the interface (the “public part”); the
implementation is hidden by “access control”.
10
CS 340
Two Ways of Reusing Classes
• Composition: One class has another as a part (indicated
by the diamond “aggregation” symbol).
BottleOfBeer
CaseOfBeer
Tavern
+open():void
+lift(height:int):void
+tilt(angle:int):void
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
BottleOfRollingRock
-lowCalorie:Boolean
+open():void
+lift(height:int):void
+tilt(angle:int):void
+isLowCalorie():Boolean
CS 340
12
Polymorphism
• Different subclasses respond to the same message,
possibly with different actions.
Patron
+beerPlease():Polite
AmericanPatron
+beerPlease():Rude
BritishPatron
GermanPatron
+beerPlease():InGerman
CS 340
13
Some Java Code
Patron 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
QUESTIONS?
14
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
public String getTitle(int lectureNumber) {
LectureNotes lect;
lect = syllabus.getLecture(lectureNumber);
String s = lect.getLine(1);
return s;
}
• 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.
CS 340
Java’s Use of Memory
• Stack
• Heap
• Static variables
• Constants
• Non-RAM storage
18
19
CS 340
Java’s Primitive Types
Type
Size
Wrapper type
boolean
char
16-bit
Boolean
Character
byte
short
int
8-bit
16-bit
32-bit
Byte
Short
Integer
long
float
double
64-bit
32-bit
64-bit
Long
Float
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
Creating New Types
class MyNewType {
// definition here
}
• Now it’s legal to say
MyNewType m = new MyNewType();
22
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
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());
}
}
24
CS 340
QUESTIONS?
25
CS 340
Java design
26
CS 340
Java Design Goals
• Simple, object oriented, and familiar
• Robust and secure
• Architecture neutral and portable
• High performance
• Interpreted, threaded, and dynamic
27
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
Java vs C#
Program Structure
Operators
Choices
Loops
29
30
Java vs C#: Program Structure
Java
C#
package hello;
using System;
public class HelloWorld {
namespace Hello {
public class HelloWorld {
public static void Main(string[]
args) {
string name = "C#";
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 + "!");
}
}
// 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#: Comments
Java
C#
// Single line
// Single line
/* Multiple
/* Multiple
line */
line */
/** Javadoc documentation comments /// XML comments on a single line
*/
/** XML comments on multiple lines
*/
32
Java vs C#: Data Types
Java
C#
Primitive Types
boolean
byte
char
short, int, long
float, double
Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double, decimal
structures, enumerations
Reference Types
Object (superclass of all other classes)
String
arrays, classes, interfaces
Reference Types
object (superclass of all other
classes)
string
arrays, classes, interfaces, delegates
33
Java vs C#: Data Types
Java
C#
Conversions
Conversions
// int to String
int x = 123;
String y = Integer.toString(x); // y is
"123"
// int to string
int x = 123;
String y = x.ToString(); // y is "123"
// String to int
y = "456";
x = Integer.parseInt(y); // x is 456
// 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)
// double to int
double z = 3.5;
x = (int) z; // x is 3 (truncates
decimal)
34
Java vs C#: Constants
Java
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#: Operators
Java
C#
Comparison
== < > <= >= !=
Comparison
== < > <= >= !=
Arithmetic
+ - * /
% (mod)
/ (integer division if both operands are
ints)
Math.Pow(x, y)
Arithmetic
+ - * /
% (mod)
/ (integer division if both operands
are ints)
Math.Pow(x, y)
Assignment
= += -= *= /= %= &= |= ^= <<=
>>= >>>= ++ --
Assignment
= += -= *= /= %= &= |= ^= <<=
>>= ++ --
Bitwise
& | ^ ~ << >> >>>
Bitwise
& | ^ ~ << >>
36
Java vs C#: Operators
Java
C#
Logical
&& || & | ^ !
Logical
&& || & | ^ !
Note: && and || perform short-circuit
logical evaluations
Note: && and || perform short-circuit
logical evaluations
String Concatenation
+
String Concatenation
+
37
Java vs C#: Choices
Java
C#
greeting = age < 20 ? "What's up?" :
"Hello";
greeting = age < 20 ? "What's up?" :
"Hello";
if (x < y)
System.out.println("greater");
if (x < y)
Console.WriteLine("greater");
if (x != 100) {
x *= 5;
y *= 2;
}
else
z *= 6;
if (x != 100) {
x *= 5;
y *= 2;
}
else
z *= 6;
38
Java vs C#: Choices
Java
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 fallthrough
case "blue": b++; break;
case "green": g++; break;
default: other++; break;
// break necessary on default
}
39
Java vs C#: Loops
Java
C#
while (i < 10)
i++;
while (i < 10)
i++;
for (i = 2; i <= 10; i += 2)
System.out.println(i);
for (i = 2; i <= 10; i += 2)
Console.WriteLine(i);
do
i++;
while (i < 10);
do
i++;
while (i < 10);
for (int i : numArray) // foreach
construct
sum += i;
foreach (int i in numArray)
sum += i;
40
Java vs C#: Loops
Java
C#
// for loop can be used to iterate through
any Collection
import java.util.ArrayList;
// foreach can be used to iterate
through any collection
using System.Collections;
ArrayList<Object> list = new
ArrayList<Object>();
list.add(10); // boxing converts to
instance of Integer
list.add("Bisons");
list.add(2.3); // boxing converts to
instance of Double
ArrayList list = new ArrayList();
for (Object o : list)
System.out.println(o);
foreach (Object o in list)
Console.WriteLine(o);
list.Add(10);
list.Add("Bisons");
list.Add(2.3);
41
Java vs C#: Arrays
Java
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]);
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";
string[] names = new string[5];
names[0] = "David";
float twoD[][] = new float[rows][cols];
twoD[2][0] = 4.5;
float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;
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[][] jagged = new int[3][] {
new int[5], new int[2], new int[3]
};
jagged[0][4] = 5;
CS 340
QUESTIONS?
42