Intro to Computer Science & Programming. A Cranes Club Initiative

Similar documents
Object Oriented C# Classes. The OO features of C# are very similar to Java. We ll point the exceptions along the way. 1. A simple C# class.

Inheritance (Outsource: )

ITI Introduction to Computing II

ITI Introduction to Computing II

Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

First IS-A Relationship: Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Inheritance and Substitution (Budd chapter 8, 10)

More Relationships Between Classes

Introduction to Object-Oriented Programming

SPOILER Link to solutions and explanations:

Chapter 15: Object Oriented Programming

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Static and Dynamic Behavior עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מובסס על הרצאות של אותו קורס שניתן בשנים הקודמות ע "י ד"ר גרא וייס

Reusing Classes. Hendrik Speleers

Intro to Computer Science & Programming. A Cranes Club Initiative

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Previously, on Lesson Night... From Intermediate Programming, Part 1

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Lecture 6 Introduction to Objects and Classes

CS1150 Principles of Computer Science Objects and Classes

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

QUESTIONS FOR AVERAGE BLOOMERS

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

CS1020: DATA STRUCTURES AND ALGORITHMS I

Basic Object-Oriented Concepts. 5-Oct-17

OVERRIDING. 7/11/2015 Budditha Hettige 82

CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism

Android/Java Lightning Tutorial JULY 30, 2018

Week 11: Class Design

AP CS Unit 6: Inheritance Notes

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Object Orientated Programming Details COMP360

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

Software Development. Modular Design and Algorithm Analysis

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Inheritance. Transitivity

CIT Special final examination

Inheritance & Polymorphism. Object-Oriented Programming

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Example: Count of Points

Interfaces. CSE 142, Summer 2002 Computer Programming 1.

Interfaces. Readings and References. Recall the discussion of ArrayLists. How can we manage lists of objects? Reading


Advanced Object Oriented PHP

CS 61B Discussion 4: Inheritance Fall 2018

Object-Oriented Concept

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Object-Oriented ProgrammingInheritance & Polymorphism

Inheritance and Polymorphism

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Inheritance and Substitution גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

Inheritance and Encapsulation. Amit Gupta

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Principles of Object Oriented Programming. Lecture 4

C08: Inheritance and Polymorphism

ECE 122. Engineering Problem Solving with Java

Chapter 2: Java OOP I

Spring 2019 Discussion 4: February 11, 2019

CS 320 Introduction to Software Engineering Spring March 06, 2017

Inheritance and Interfaces

11/12/12. Objectives DESIGN PATTERNS. Design Pattern. Defined Design Patterns. Applying Design Patterns. Motivating Example

Object-Oriented Programming

Concepts of Object Oriented Programming

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Lecture 18 CSE11 Fall 2013 Inheritance

Java Fundamentals (II)

Computer Science 4U Unit 1. Programming Concepts and Skills Modular Design

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

Create a Java project named week10

Object oriented programming Concepts

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Object Orientated Analysis and Design. Benjamin Kenwright

Building custom components IAT351

CS 31: Intro to Systems Threading & Parallel Applications. Kevin Webb Swarthmore College November 27, 2018

Introduction to Programming

Example: Count of Points

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Programming in C# Inheritance and Polymorphism

What is Inheritance?

Object Oriented Programming

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

Lecture 2: Java & Javadoc

Inheritance. For example, to zoom in on the deer family (cervid), we could make a tree like the following.

Object Oriented Programming. Michał Bereta

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

COP 3330 Final Exam Review

Transcription:

Intro to Computer Science & Programming A Cranes Club Initiative

Object-Oriented Programming and Design Data Structures

Object-Oriented Programming and Design Inheritance Abstract classes Polymorphism Interfaces Encapsulation Object composition

Inheritance The ability for a parent class (base class) to pass down behaviors and properties to a child class (sub class). Child class may introduce new methods or override old ones. The extends keyword. A child class extends a parent class. All classes implicitly extend the Object class

Some Keywords public - all classes can access it. protected - all descendants and classes in the same package can access it. private - no other classes can access it. no keyword - classes within the same package can access it. static - only one, not many. Class method/variable vs. instance method/variable.

Inheritance class Mammal private static int count = 0; protected int height, weight; protected boolean backbone, heart, lungs, stomach, eyes, mouth, nose, ears; protected String name; class Dog extends Mammal protected boolean muzzle, loyalty; protected void bark() protected void chasetail() protected void wagtail() protected void dig() Mammal() count++; protected void eat() protected void sleep() protected void procreate() protected void die() count--; class Cat extends Mammal protected boolean claw, ego; protected void meow() protected void catchrodents() protected void lickfur() protected void spithairball()

Human Beings class Homonidae extends Primates protected static final boolean legslongerthanarms = true, opposeablethumbs = true, notail = true; void walkontwos() void maketools() final class HumanBeings extends Homonidae // However, man is created to attain his perfection not only // through the dominion and autonomy of the Principle itself, // but also by accomplishing his own portion of responsibility // in passing through this period public static final boolean portionofresponsibility = true;

Multiple Inheritance The ability to inherit from multiple classes. In Java (and several other OOP languages), this is not allowed. Why not? Confusion, ambiguous inheritance.

Let s Illustrate Using DP

Let s Illustrate Using DP Which version of offering() will this call? class God void offering() System.out.println("I live for the sake of others."); class Satan void offering() System.out.println("I live for the sake of myself!"); class FallenHuman extends God, Satan FallenHuman adam = new FallenHuman(); adam.offering();

Abstract Classes A class that s meant to be an outline, not an implementation. Cannot create objects of abstract class. May be partially implemented. Must use the abstract keyword to declare the class and any abstract methods.

Let s Revisit Mammal class Mammal private static int count; protected int height, weight; protected boolean backbone, heart, lungs, stomach, eyes, mouth, nose, ears; protected String name; Mammal() count++; protected void eat() protected void sleep() protected void procreate() protected void die() count--; Mammal a; a = new Mammal(); abstract class Mammal private static int count; protected int height, weight; protected boolean backbone, heart, lungs, stomach, eyes, mouth, nose, ears; protected String name; Mammal() count++; abstract protected void eat(); abstract protected void sleep(); abstract protected void procreate(); protected void die() count--; Mammal a; //allowed a = new Mammal(); //not allowed!

Polymorphism The ability to dynamically assign an object s behavior. Child classes override methods of base classes. Allows for code reuse, better organization and easier maintenance.

Polymorphism abstract class Pet String _name = ""; Pet(String name) _name = name; abstract void makesound(); class Dog extends Pet Dog() super("fido"); Dog(String name) super(name); void makesound() System.out.println("Woof woof!"); class Cat extends Pet Cat() super("griz"); Cat(String name) super(name); void makesound() System.out.println("Meow meow!"); Pet a; a = new Dog(); a.makesound(); a = new Cat(); a.makesound(); //this will print "woof woof!" //this will print "meow meow!"

Interfaces An outline of behaviors to follow. Contains only public, abstract methods. The implements keyword. A child class implements an interface. Unlike inheritance, you can implement multiple interfaces.

Interfaces multiple interfaces allowed interface CanFly void fly(); interface CanSwim void swim(); class Puffin implements CanFly, CanSwim public void fly() System.out.println("Hey I'm flying cuz I'm a puffin!"); public void swim() System.out.println("Hey I'm swimming cuz I'm a puffin!"); class Penguin implements CanSwim public void swim() System.out.println("Hey I'm swimming cuz I'm a penguin!"); class Pigeon implements CanFly public void fly() System.out.println("Hey I'm flying cuz I'm a pigeon!");

Abstract Classes vs Interfaces They are similar, but when to use which? If you re just outlining behaviors, interface is fine. If you want to build off of existing behavior, abstract classes will do.

Encapsulation Data/information hiding Create getter and setter functions for properties. Protect your privacy! Allows user to be unaffected by implementation changes.

Encapsulation Recall the Bear class from the quiz: /* This is not good. Both height and weight are exposed and can be manipulated by anybody with access to a Bear object. */ class Bear int height; int weight; String species; String color; void maul() void hibernate() void climb() void swim() /* This is better. Height and weight are now read-only to the user. A user can no longer modify them directly. */ class Bear private int height; private int weight; public int getheight() return height; public int getweight() return weight; String species; String color; void maul() void hibernate() void climb() void swim() Bear smokey = new Bear(); smokey.weight = 400; Bear smokey = new Bear(); int smokeyweight = smokey.getweight();

Composition A class that s composed of objects of other classes within its definition. Has-a relationship, as opposed to inheritance which is is-a. Better than inheritance at adapting to code change.

Composition vs Inheritance Let s revisit the Penguin/Puffin/Pigeon example. What if we added glide() to the CanFly interface and dive() to the CanSwim interface? We have to update the code for Penguin, Puffin, and Pigeon.

Composition vs Inheritance Puffin s code doubles! interface CanFly void fly(); void glide(); interface CanSwim void swim(); void dive(); //new! //new! class Puffin implements CanFly, CanSwim public void fly() System.out.println("Hey I'm flying cuz I'm a puffin!"); public void glide() System.out.println("Hey I'm gliding cuz I'm a puffin!"); public void swim() System.out.println("Hey I'm swimming cuz I'm a puffin!"); public void dive() System.out.println("Hey I'm diving cuz I'm a puffin!");

Composition vs Inheritance Instead of Puffin being a bird that can fly and can swim, how about a Puffin being a bird that has flying behavior and has swimming behavior? Puffin is a flying and swimming bird vs. Puffin has flying and swimming capabilities. If behavior details change, Puffin class does not change.

Composition vs Inheritance Puffin s code stays the same. interface FlyAbility void fly(); interface SwimAbility void swim(); class Puffin private SwimAbility swimming; private FlyAbility flying; void fly(flyability ability) flying = ability; flying.fly(); void swim(swimability ability) swimming = ability; swimming.swim(); class PuffinFly implements FlyAbility public void fly() System.out.println("Hey I'm flying cuz I'm a puffin!"); class PuffinGlide implements FlyAbility public void fly() System.out.println("Hey I'm gliding cuz I'm a puffin!"); class PuffinSwim implements SwimAbility public void swim() System.out.println("Hey I'm swimming cuz I'm a puffin!"); class PuffinDive implements SwimAbility public void swim() System.out.println("Hey I'm diving cuz I'm a puffin!");

Data Structures and Algorithms Array ArrayList HashTable Stack

Array A linear sequence of items accessible by index. Pros: Fast random access. Cons: Fixed-size (i.e. cannot grow/shrink). Average search speed. String [] array = "peter", "piper", "picked", "a", "peck"; [] works too System.out.println(array[0]); //this would print "peter" System.out.println(array[2]); //this would print "picked" System.out.println(array[4]); //this would print "peck" // int array

ArrayList Dynamic version of Array. Pros: Fast random access. Cons: Overhead costs to grow/shrink. Still average search speed. import java.util.arraylist; ArrayList<String> arraylist = new ArrayList<String>(Arrays.asList("peter", "piper", "picked")); arraylist.add("a"); arraylist.add("peck"); System.out.println(arrayList.get(0)); //this would print "peter" System.out.println(arrayList.get(2)); //this would print "picked" System.out.println(arrayList.get(4)); //this would print "peck" System.out.println(arrayList); //this would print "[peter, piper, picked, a, peck]"

Hashtable A table of key-value pairs. Look-up items using the key. Pros: Fast look-up speed. Cons: Can take up a lot of extra space. import java.util.hashtable; Hashtable<String, String> hometowns = new Hashtable<String, String>(); hometowns.put("ten-seng Guh", "Taipei, Taiwan"); hometowns.put("stephen Curry", "Akron, Ohio"); hometowns.put("sophia Guh", "Sleepy Hollow, New York"); System.out.println(hometowns.get("Ten-Seng Guh")); //this will print "Taipei, Taiwan"

Stack A collection of items that are accessed in LIFO (last in, first out) order. Pros: Good for accessing latest items. Cons: Bad for accessing earliest items. import java.util.stack; Stack<String> shoppingcarts = new Stack<String>(); shoppingcarts.push("cart 1"); shoppingcarts.push("cart 2"); shoppingcarts.push("cart 3"); String gimmecart = shoppingcarts.pop(); System.out.println(gimmeCart); //this will print "Cart 3"

Homework 2 Write a Blackjack program! Due July 14th (you have two weeks!) First think about your design: what data structure would you use to represent a deck of cards? How would you design the card class?