01_OO_Composition PDF - NC State University

Document Details

Uploaded by Deleted User

NC State University

null

null

Tags

object-oriented programming java programming computer science software development

Summary

This document is a set of lecture notes on object-oriented programming for NC State University, covering topics such as constructors, object construction methods in java programming and reference semantics.

Full Transcript

OO Programming and Composition Zybooks: Chapters 1-10 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 1 Object-Oriented Programming Reasoning about a...

OO Programming and Composition Zybooks: Chapters 1-10 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 1 Object-Oriented Programming Reasoning about a program as a set of objects rather than as a set of actions Object: A programming entity that contains state and behavior – State: internal data of an object (fields or instance variables) What an object knows – Behavior: set of actions performed by the object (instance [non-static] methods) What an object can do Class: a blue print for an Object – Defines how we construct and work with objects CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 2 Constructors Classes can have multiple constructors – Different signatures – number and type(s) of parameters Default constructor (no parameters) automatically available if you have no defined constructors After you define one constructor, you have to write a default constructor Programming Paradigm – One-Path of Construction: one constructor contains initialization code – all other constructors call it – Every object goes through a common code path CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 3 Object Construction Recipe r = new Recipe(“Chili”, 4); //name, number of servings 1. Creates a Recipe reference, r 2. Creates a Recipe object 3. Calls one of the possibly many Recipe constructors and passes any parameters 4. Assigns the newly created object to be stored in reference variable r CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 4 Object Construction Recipe r = new Recipe(“Chili”, 4); 1. Creates a Recipe reference, r 2. Creates a Recipe object 3. Calls one of the possibly many r Recipe constructors and passes any parameters 4. Assigns the newly created object to be stored in reference variable r CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 5 Object Construction Recipe r = new Recipe(“Chili”, 4); 1. Creates a Recipe reference, r 2. Creates a Recipe object Recipe 3. Calls one of the possibly many r Recipe constructors and passes name any parameters 4. Assigns the newly created object to be stored in reference variable r numServings CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 6 Object Construction Recipe r = new Recipe(“Chili”, 4); “Chili” 1. Creates a Recipe reference, r 2. Creates a Recipe object Recipe 3. Calls one of the possibly many r Recipe constructors and passes name any parameters 4. Assigns the newly created object to be stored in reference variable r numServings 4 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 7 Object Construction Recipe r = new Recipe(“Chili”, 4); “Chili” 1. Creates a Recipe reference, r 2. Creates a Recipe object Recipe 3. Calls one of the possibly many r Recipe constructors and passes name any parameters 4. Assigns the newly created object to be stored in reference variable r numServings 4 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 8 Reference Semantics Reference Semantics: behavior where variables refer to a common value when assigned to each other or when passed as a parameter – Object variables don’t store the object directly; instead they store the object’s location in memory “Chili” Reference Objects in Java use reference semantics Efficiency: copying large Recipe objects takes time r name Sharing: can share information when calling methods Primitives use value semantics numServings 4 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty Value 9 Reference Semantics public class Recipe { private String name; Curry public void updateName(String name) { if (name != null && name.length() != 0) this.name = name; r1 name } public static void main(String [] args) { r2 name Recipe r1 = new Recipe(“Curry”); r3 Recipe r2 = new Recipe(“Chili”); Recipe r3 = r2; r3.updateName(“Super Mega Hot Chili!”); Chili Super Mega Hot Chili } } CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 10 Reference Semantics Exercise Current Line output int x = 0; int [] a = new int ; main x 0 a 0 0 0 0 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 11 Reference Semantics Exercise Current Line output x = x + 1; main x 1 0 a 0 0 0 0 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 12 Reference Semantics Exercise Current Line output mystery(x, a); main mystery x 1 x 1 a a 0 0 0 0 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 13 Reference Semantics Exercise Current Line output x = x + 1; 2 [0, 0, 1, 0] a[x] = a[x] + 1; sysout(x + “ “ + Arrays.toString(a); main mystery x 1 x 2 1 a a 0 0 1 0 0 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 14 Reference Semantics Exercise Current Line output sysout(x + “ “ + Arrays.toString(a); 2 [0, 0, 1, 0] x = x + 1; 1 [0, 0, 1, 0] main x 1 2 a 0 0 1 0 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 15 Reference Semantics Exercise Current Line output mystery(x, a); 2 [0, 0, 1, 0] 1 [0, 0, 1, 0] main mystery x 2 x 2 a a 0 0 1 0 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 16 Reference Semantics Exercise Current Line output x = x + 1; 2 [0, 0, 1, 0] a[x] = a[x] + 1; sysout(x + “ “ + Arrays.toString(a); 1 [0, 0, 1, 0] 3 [0, 0, 1, 1] main mystery x 2 x 3 2 a a 0 0 1 0 1 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 17 Reference Semantics Exercise Current Line output sysout(x + “ “ + Arrays.toString(a); 2 [0, 0, 1, 0] 1 [0, 0, 1, 0] 3 [0, 0, 1, 1] 2 [0, 0, 1, 1] main x 2 a 0 0 1 1 CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 18 Dereferencing an Object Dereference: to access data or methods of an object – Use the dot notation – Specify which object to dereference and what field or method to access Recipe r = new Recipe(“Chili”); String name = r.getName().toUpperCase(); r.updateName(“Super Mega Hot Chili”); CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 19 Null References null: A built in value that does not refer to any object – Uninitialized object variables are set to null Uses of null – Initialize a local object variable Recipe r = null; – Check if an object is null if (r == null) { … } – Pass null as a parameter Useful in some cases when use of parameter is unknown Be prepared for that method to throw an exception! – Return null from a method Indicate failure or that something wasn’t found CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 20 NullPointerException null cannot be dereferenced! – null has no methods or data Recipe r = new Recipe(); //default const. String s = r.getName().toUpperCase(); r name null CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 21 Composition and Delegation Creating a class from existing classes – Classes have members (fields) that are instances of other classes Our class works with the object fields by calling methods (and fields) of the object – An instance of the original class provides functionality for the class you’re writing – You’re delegating to the field through its methods – Delegation is a way of extending and reusing a class CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 22 Abstraction & Encapsulation Abstraction: Distancing between ideas and details – Can use objects without knowing how they work – Example: Phone Encapsulation: Hiding the implementation details of an object from the clients of the object – Protects data from unwanted access – Clients cannot directly access of modify its internal workings – nor do they need to do so – Encapsulation leads to abstraction CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 23 Steps for Achieving Encapsulation Make fields private Ensure class invariants – Class Invariant: a property that is true of every object/instance of a class – An assertion about an object’s state that is true for the lifetime of that object – Enforce within public methods and call public methods within class (e.g. from constructor) – Example: a student id number should never be negative If class contains Object fields, defensively copy the object to ensure immutability CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 24 Method Overriding Every object you create is an Object Object has useful methods that you can override – toString() – equals() – hashCode() CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 25 The Object Class Object is a (direct or indirect) superclass of all Java classes – Every object you construct is an Object Contains defines nine methods that you can override – Override: provide your own implementation of the method Method Purpose String toString() Returns a String representation of the object. boolean equals(Object o) Returns true if some other object is “equal to” this one. int hashCode() Returns a hash code value for the object. CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 26 The toString() method Called automatically when ever a String is concatenated with an Object If you don’t override toString(), the default output is something like – “ClassName@d24606bf” – Name of the class followed by the hash code Have to override toString() so that interesting and relevant information is printed – Convention: “ClassName[fieldName=fieldValue,…]” CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 27 Curry The equals() method r1 name Called when want to compare objects r2 name r3 Super Mega Hot Chili Default behavior of equals()? – The same thing as ==, which compares object references to see if two objects point to SAME object The equals() method has a parameter of type Object – We must cast the parameter to the same type of object as the class to compare the fields CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 28 The hashCode() method Method that uses an algorithm to compute an unsigned integer value that is likely to be unique for different objects When two or more objects that we would consider different have the same hash code we have a collision – Try to write hash functions that minimize collision – Hash functions scramble info about the instance fields to create the integer value Typically prime numbers are used hashCode() should be compatible with equals() – Objects that are the same should hash to the same value – Use the same fields to compare for equality and create the hash code If you override equals(), you must override hashCode() – This is a Java invariant! CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 29 equals() and hashCode() Let Eclipse write your equals() and hashCode() methods for you You should know how to write equals() methods without code generation help – See the textbooks for suggested structure You do not need to know how to write hashCode() method, but need to know what it is CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 30 Implicit Parameter Implicit Parameter: the object being referenced during the call of an instance method Provides knowledge of what specific object the method will operate on We can access the implicit parameter using the keyword this Calling an object’s field, like x, is compiled to this.x CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 31 Welcome to Recipe Book The Recipe Book is an electronic cookbook. You can collect recipes. Maybe one day, we’ll use the info to create an automated chef? We’re going to focus on a module for Stews What makes a stew? CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 32 Stew Composition CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 33 Stock Implementation (POJO) public class Stock { private String name; private double amount; private String description; public Stock(String name, double amount, String description) { this.name = name; this.amount = amount; this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 34 Stock Implementation (POJO) public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean equals() { … } public int hashCode() { … } public String toString() { … } } } CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 35 Stew Implementation Construction import java.util.ArrayList; // Parameterized constructor public class StewRecipe { public StewRecipe(String name) { // Fields – composition relationship this.name = name; private Stock stock; Declaration proteins = new ArrayList(); private ArrayList proteins; vegetables = new AL(); private ArrayList vegetables; seasonings = new AL(); private ArrayList seasonings; } public String getRecipe() { // Field – composition with Java API String rtn = stock.toString() + “\n”; private String name; rtn += proteins.toString() + “\n”; rtn += vegetables.toString() + “\n”; // Default constructor rtn += seasonings.toString(); public StewRecipe() { return rtn; Use this(“Stew”); } } } CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 36 Composition Summary Using objects within another class allows for the creation of custom objects – Example: Stew has Stock, Proteins, Vegetables, Seasonings Start with primitive types and build more complex objects from those types – Example: Stock has name (String), amount (double), description (String) The container class can define its own methods to call the methods of its instance variables – This is delegation! – Example: Stew.toString() delegates to the objects’ toString() methods CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 37 Class Design Paradigm Do not provide any functionality that does not have a clear use Control access to an object’s state! – Omit mutators (methods that change state) if they are not needed – Limit object creation to the constructor (not always possible) “Classes should be immutable unless there’s a very good reason to make them mutable… If a class cannot be made immutable, limit it’s mutability as much as possible.” Joshua Bloch CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 38 Class Design Paradigm Classes should have cohesion – The extent to which the code for a class represents a single abstraction (idea) – Allows for reusability of the class in other programs The Recipe class represents only things a Recipe can do and knows. – A Recipe should not perform console input and output – A Recipe should not ensure that a specific ingredient is constructed correctly. CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 39 Lab 00: Installation Lab 00 checks your environment setup. – Individual lab – Due All Sections: Thursday, August 29th at 11:45pm – CSC 216 ONLY students – you’re encouraged to make sure your environment is up to date! Demo functionality – Demo in person during office hours – Record and submit a video demo Use provided GitHub repo (csc217-L0-) CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 40 Guided Project 1 Install Eclipse and plug-ins needed for CSC 216 Learn how to use Eclipse & GitHub Start WolfScheduler program – Guided Project 1 – Review pre-req materials (CSC 116 and equivalent) including composition & file I/O – Due Thursday, September 5, 2024 @ 11:45pm – Late Deadline Saturday, September 7, 2024 @ 11:45pm Use provided GitHub repo (csc216-GP1--) CSC 216: Software Development Fundamentals © NC State CSC 216 Faculty 41

Use Quizgecko on...
Browser
Browser