Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 340 DATA STRUCTURES Lecture: Everything is an Object.

Similar presentations


Presentation on theme: "CS 340 DATA STRUCTURES Lecture: Everything is an Object."— Presentation transcript:

1 CS 340 DATA STRUCTURES Lecture: Everything is an Object

2 OOP or… Object Oriented Programming CS 340 2

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 3

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 4

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 5

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 6

7 Example Suppose I’ve defined this class in Java: To make one, I type BottleOfBeer myBeer = new BottleOfBeer(); If I want myBeer opened, I say myBeer.open(); CS 340 7

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 CS 340 8 BottleOfBeer myBeer;

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”. CS 340 9

10 Two Ways of Reusing Classes Composition: One class has another as a part (indicated by the diamond “aggregation” symbol). CS 340 10

11 Two Ways of Reusing Classes Inheritance: One class is a specialized version of another (indicated by the triangle “inheritance” symbol). CS 340 11

12 Polymorphism Different subclasses respond to the same message, possibly with different actions. CS 340 12

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 13

14 QUESTIONS? CS 340 14

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 15

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 16

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. CS 340 17 public String getTitle(int lectureNumber) { LectureNotes lect; lect = syllabus.getLecture(lectureNumber); String s = lect.getLine(1); return s; }

18 Java’s Use of Memory Stack Heap Static variables Constants Non-RAM storage CS 340 18

19 Java’s Primitive Types CS 340 19 TypeSizeWrapper type boolean-Boolean char16-bitCharacter byte8-bitByte short16-bitShort int32-bitInteger long64-bitLong float32-bitFloat double64-bitDouble void-Void

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 20

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 21

22 Creating New Types class MyNewType { // definition here } Now it’s legal to say CS 340 22 MyNewType m = new MyNewType();

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 CS 340 23 class MyClass { int a; YourClass b; float memberFunction(int x, float f) { return 0; }

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 24

25 QUESTIONS? CS 340 25

26 Java design CS 340 26

27 Java Design Goals Simple, object oriented, and familiar Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamic CS 340 27

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 28

29 Java vs C# Program Structure Operators Choices Loops CS 340 29

30 Java vs C#: Program Structure 30 JavaC# 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#: Comments 31 JavaC# // 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 Types 32 JavaC# Primitive Types boolean byte char short, int, long float, double Reference Types Object (superclass of all other classes) String arrays, classes, interfaces 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, delegates

33 Java vs C#: Data Types 33 JavaC# 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#: Constants 34 JavaC# // 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 35 JavaC# 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#: Operators 36 JavaC# Logical && || & | ^ ! Note: && and || perform short-circuit logical evaluations String Concatenation + Logical && || & | ^ ! Note: && and || perform short-circuit logical evaluations String Concatenation +

37 Java vs C#: Choices 37 JavaC# 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#: Choices 38 JavaC# 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#: Loops 39 JavaC# 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#: Loops 40 JavaC# // for loop can be used to iterate through any Collection import java.util.ArrayList; ArrayList list = new ArrayList (); list.add(10); // boxing converts to instance of Integer list.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#: Arrays 41 JavaC# 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;

42 QUESTIONS? CS 340 42


Download ppt "CS 340 DATA STRUCTURES Lecture: Everything is an Object."

Similar presentations


Ads by Google