Presentation is loading. Please wait.

Presentation is loading. Please wait.

EECE 310: Software Engineering

Similar presentations


Presentation on theme: "EECE 310: Software Engineering"— Presentation transcript:

1 EECE 310: Software Engineering
Lecture 2: Understanding Objects in Java and Types (Stuff you should be familiar with …)

2 What will we cover in this class?
Objects and variables on the stack and heap Mutable and Immutable objects Procedure call semantics Type checking Hierarchy Conversions Overloading Program structures: classes, interfaces etc.,

3 What we will NOT cover in this class
Basics such as loops, function calls, objects etc. Read an introductory Java book for these Internals of Java language/semantics Except as necessary to understand the concepts Advanced libraries for graphics, networking, etc. Read a good library tutorial, but not necessary for this class (we will cover some of these as we go along)

4 Why Java ? Automated memory management Strong type safety for security
Portability through VM Excellent in-built libraries for networking/graphics

5 Brief history of Java … Developed by James Gosling at Sun in 1995
Initially code-named ‘Oak’, was meant to target small, embedded devices (such as microwaves) Became popular with the growth of WWW – Netscape had support for Applets Mature alternative to C/C++ by late nineties MS develops C# as alternative to Java (early 2000) Today: Java used mainly in server/business apps

6 What will we cover in this class?
Objects and variables on the stack and heap Mutable and Immutable objects Procedure call semantics Type checking Hierarchy Conversions Overloading Program structures: packages, modules etc.,

7 Objects and Variables Variables Objects
Confined to single context: allocated on stack Types: Primitive (such as int) or objects references Must be initialized before use (or fail compilation) Objects Shared among multiple procedure contexts Allocated on heap using new operator Can be initialized after creation (by constructor)

8 Variables and Objects: Example
heap int i = 6; int j; int [] a = {1, 3, 5, 7, 9}; int [] b = new int[3]; String s = “abcdef”; String t = null; j = i; b = a; t = s; i = 6 j = 6 j a b “abcdef” s t = null t Stack

9 Object references All object references are uninitialized initially
Can be initialized to null, but not necessary Need to explicitly allocate the object on the heap or assign it to (the start of ) an existing object No pointer arithmetic possible once assigned No need to explicitly de-allocate the reference (garbage collection frees it when not in use) Can be passed to procedures and copied around

10 Example of Objects and References
{ Object b = null; Object a = new Object(); b = a; } c = b.hashCode(); Reference b is allocated on stack and initialized to null Reference a is allocated on stack Object is allocated on the heap and reference a points to it b and a both point to the same object a goes out of scope, so only b points to object b goes out of scope too, so nobody points to the object. Object is automatically reclaimed by garbage collector

11 Object Mutability By default, Java objects are mutable Modifications made through one reference will be visible when the object is accessed through another reference to the object Example: Arrays int [] a = {1, 3, 5, 7, 9}; a[3] = -1; b = a; b[4] = -2;

12 Exception: Immutable objects
State of immutable object never changes once it is assigned Example: String object String s1 = “abcdef”; String s2 = “ghij”; String s3 = s1; s3 = s1 + s2; String s4 = s3; s4 = s2 + s1; “abcdef” “ghij” “abcdefghij” “ghijabcdef” Heap

13 Mid-term like question
What happens after these ? int[ ] a = {1, 2, 3}; int[ ] b = new int[2]; int[] c = a; int x = c[0]; b[0] = x; a[1] = 6; x = b[1]; int y = a[1]; What happens after these ? String s1 = “ace”; String s2 = “f”; String s3 = s1; String s4 = s3 + s2; s1 = s4; s4 = s1 + s2;

14 Java Calling Convention
Some textbooks will say the following In Java, Objects are passed by reference, and primitives are passed by value… […] This is wrong ! Java has only call-by-value Both primitive types and object references are passed by value i.e., copied in to the stack frame Can modify the object through the passed in reference provided object is not immutable

15 Calling convention: Call-by-value
stack void foo(int a, int[] b) { a = a + 1; b[0] = 3; } heap a = 11 a = 10 b 3 int[] q = new int[3]; int p = 10; foo (p, q); // What are p and q’s value ? p = 10 q

16 Method calls in Java – Example 1
public static void swap(int a, int b) { int temp = a; a = b; b = temp; } m = 5; n = 10; swap(m, n); // What are the values of m and n here ? // (HINT: It’s not what you expect)

17

18 Roadmap [Last time] Variables - Primitive types vs. objects
Stored: on the stack or heap Mutable and Immutable objects Procedure call semantics Type checking Hierarchy Conversions Overloading Program structures: classes, interfaces etc., 18

19 Method calls in Java – Example 2
public static void findAndRemove(int[ ] a, int m) { if (a ==null) return; // avoid null pointer exception for (int i = 0; i < a.length; i++) { if (a[i]==m) a[i] = 0; } int[ ] b = { 0, 2, 4, 6, 8 }; findAndRemove( b, 2 ); // What is the value of the array b here ?

20 Method calls in Java: Example 3
public static void padChars(String xxx, int n){ for (int i = 0; i < n; i++) xxx = xxx + “a”; } String str = “hello”; padChars(str, 5); // What is the value of str ? hashCode

21 Summary (Objects and Variables)
Variables can be primitive types or references Variables are allocated on the stack References point to objects allocated on heap Objects are automatically garbage collected when there is no reference pointing to them Objects are mutable by default i.e., can be modified. Exception to this is the built-in String object Java supports only call-by-value References passed by value give the illusion of objects being passed by reference

22 Roadmap Objects and variables on the stack and heap Type checking
Mutable and Immutable objects Procedure call semantics Type checking Hierarchy Conversions Overloading Program structures: classes, interfaces etc.,

23 Type Safety Java is strongly typed (i.e., type-safe)
No “unsafe” casts are possible (e.g., reference to int) Type-safety enforced by compiler (by language design) Memory safety follows from type-safety No writing past the end of an object (buffer overflows) Automatic garbage collection provided by runtime No dangling pointer errors No double-free errors

24 Type Checking Consider the following function:
public static void findAndRemove(int[] a, int m); The compiler checks the call-site of the function to ensure that it matches its type-signature. int[] b = [0, 2, 4, 8, 10]; int n = 5; String s = “hello”; findAndRemove(b, n); // Is this legal ? findAndRemove(n, b); // What about this ? findAndRemove(s, n); // Ok, what about this ?

25 Type Hierarchy Consider a type S which is a sub-type of T (say S is derived from T)., S can be substituted in place of T whenever a function/assignment expects T. Example: All objects in Java are sub-types of Object, which defines an equals method. String s1 = “hello”; Object O1 = s1; if ( O1.equals(“hello”) ) ….; // legal if ( O1.length() ) …. ; // illegal

26 Apparent vs. Actual type
Apparent type -- the type inferred from declarations Actual type -- the type received at (object) creation NOTE: Apparent type is a super-type of the actual type Statement Apparent type Actual type String s = “abcdef”; String Object o = s; Object s = o; Illegal ! s = (String)o; int [] a = {0, 1, 2}; Int[] o = a; int[] a [2] = 3; Int

27 Type Checking Type-checking is done using the apparent type of an object, NOT its actual type If the actual type supports a member function, but the apparent type does not, it is ILLEGAL to invoke the member directly However, if we cast the apparent type of an object to its actual type, we can invoke its member functions String s1 = “hello; Object O1 = s1; if ( ( (String)O1 ).length() ) …. ; // legal NOTE: If the actual type of the object does not match the cast type, a runtime exception is raised (ClassCastException) Example: (Integer)(O1) will raise a runtime exception

28 Group Activity Which of the following is legal ? For the ones that are legal, determine the result (or exception). Object o = “abc”; Boolean b = new Boolean( o.equals(“a, b, c”) ); char c = o.charAt(1); Object o2 = b; String s = o; String t = (String) o; String u = (String) o2; char d = t.charAt(1);

29 Type overloading Same function can have multiple definitions based on argument types and/or return value static int compare(int, float); // defn 1 static int compare(float, float); // defn 2 static int compare(float, int); // defn 3 The compiler “knows” which definition to call depending on the type of the parameters compare(5.0, 3); // Calls defn 3 compare(5.0, 6.0); // Calls defn 2 compare(3, 5.0); // Calls defn 1

30 Implicit Type Conversions
Often, the compiler will implicitly convert one primitive type to another (widening) int => float int => long But long => int, float=>int NOT possible So which version of compare do these call ? compare(3, 5.0); // Definition 1 or Definition 2 ? compare(5.0, 6); // Definition 2 or Definition 3 ?

31 Matching Rule for Implicit Conversions
“Most specific” method Find the method that matches the types of the parameters with the least number of type conversions Example: compare(3, 5.0); // Calls definition 1 compare(5.0, 3.0); // Calls definition 2 compare(3, 4); // What about this one ? NO “most specific method”  compilation error Can be avoided by explicit type-casting in the call such as compare(3, (float)4 );

32 Summary (Types) Java has strong-type checking Method overloading
Apparent type must match during calls Actual type needed to invoke member functions Method overloading Compiler implicitly converts one type into another (widening) for method calls Call matching done with the “most specific match”

33 Roadmap Objects and variables on the stack and heap Type checking
Mutable and Immutable objects Procedure call semantics Type checking Hierarchy Conversions Overloading Program structures: classes, interfaces etc.,

34 Structure of Java Programs
Methods Classes Interfaces Packages

35 Interfaces and Classes
Define new data types Do NOT have method bodies or constructors Classes Define collections of procedures Also, defined method bodies and constructors

36 public class IntQueue { // OVERVIEW: IntQueues are mutable, bounded queues of integers that // operate in first-in-first-out order, i.e., elements are always added to // the tail of the queue and are removed from its head. private Vector queue = null; private int capacity = 0; public IntQueue(int c) { // Constructor capacity = c; queue = new Vector(capacity); } //Add an element to the queue public void enQueue(int x) throws QueueIsFullException{ if (queue.size() == capacity) throw new QueueIsFullException(); queue.add(new Integer(x)); // Removes an element from the queue public int deQueue() throws QueueIsEmptyException { if(queue.isEmpty()) throw new QueueIsEmptyException(); return ( (Integer)queue.remove(0) ).intValue(); // Returns the number of elements in the queue public int size() { return queue.size(); Class (Example) Need to try this out in Eclipse

37 public interface GenericIntQueue {
// OVERVIEW: IntQueues are mutable, bounded queues of integers that // operate in first-in-first-out order, i.e., elements are always added to // the tail of the queue and are removed from its head. // MODIFIES: this // EFFECTS: if this is full, throws QueueIsFullException, // else adds x to the tail of this. public void enQueue(int x) throws QueueIsFullException; // EFFECTS: if this is empty, throws QueueIsEmptyException, // else removes one element from the head of this and returns it public int deQueue() throws QueueIsEmptyException; // EFFECTS: returns the number of elements in this. public int size(); } Interface (Example)

38 Interface (Example - cont)
public class VectorIntQueue extends SomeParentClass implements GenericIntQueue { private Vector queue = null; //implementation specific private int capacity = 0; // implementation specific public IntQueue(int c) { // Must have a Constructor capacity = c; queue = new Vector(capacity); } // Must minimally implement the functions in the // interface, namely enqueue, dequeue and size() // Can optionally implement other implementation-specific functions … Interface (Example - cont)

39 Interface (Example - cont)
public int findSmallest( GenericIntQueue gq ) { int min = gq.remove(); int minElement = min; VectorIntQueue tempQueue = new VectorIntQueue( gq.size() ); tempQueue.add( minElement ); while (gq.size() > 0) { int element = gq.remove(); if (element < min) min = element; tempQueue.add(element); } // Copy back tempQueue’s elements to gq here …. return min; Interface (Example - cont)

40 Packages Naming space Encapsulation mechanism
Queue interface and its implementation can be combined in a single package say ‘Queue’ We would then refer to the IntQueue as: Queue.IntQueue Alternatively, you could import the Queue package in your code, but this may lead to name conflicts import Queue.* Encapsulation mechanism Only public (protected) members visible outside

41 Access to public, protected, package access, and private members of a class by a client and a subclass

42 Summary (Classes, Interfaces, Packages)
Classes are used to define new data types Interfaces are used to plug in one class in lieu of another Packages are used to keep related entities together. e.g., classes and interfaces

43 What have we covered in this class?
Objects and variables on the stack and heap Mutable and Immutable objects Procedure call semantics Type checking Hierarchy Conversions Overloading Program structures: classes, interfaces etc.,

44 Miscellaneous main () method Initialization ‘static’ keyword Vectors
Multiple mains methods? Initialization Primitive types / objects ‘static’ keyword Vectors method dispatch

45 The static keyword Java methods and variables can be declared static
These exist independent of any object This means that a Class’s static methods can be called even if no objects of that class have been created and static data is “shared” by all instances (i.e., one value per class instead of one per instance class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.i == 47 StaticTest.i++; // or st1.I++ or st2.I++  st1.i == st2.i == 48

46 Method dispatch String t = “ab”; Object o = t + “c”; String r = “abc”;
boolean b = o.equals (r);

47 Before the next class Do exercises 2.1 to 2.7 in textbook for practice
Not graded, but will help in quiz preparation Get acquainted with Java Pick a partner by next lab (or we’ll pick one) Start working on Assignment 1 Involves basic Java programming Due – Thursday next week


Download ppt "EECE 310: Software Engineering"

Similar presentations


Ads by Google