Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Similar documents
Review sheet for Final Exam (List of objectives for this course)

C++ Important Questions with Answers

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Java Object Oriented Design. CSC207 Fall 2014

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Abstract Classes and Interfaces

Inheritance and Interfaces

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Introduction to Programming Using Java (98-388)

Chapter 14 Abstract Classes and Interfaces

What are the characteristics of Object Oriented programming language?

Programming Language Concepts: Lecture 2

Logistics. Final Exam on Friday at 3pm in CHEM 102

Rules and syntax for inheritance. The boring stuff

COP 3330 Final Exam Review

OBJECT ORİENTATİON ENCAPSULATİON

WA1278 Introduction to Java Using Eclipse

INHERITANCE. Spring 2019

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Programming II (CS300)

CMSC 132: Object-Oriented Programming II

Inheritance. Transitivity

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

CH. 2 OBJECT-ORIENTED PROGRAMMING

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Java Fundamentals (II)

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Programming Language Concepts: Lecture 2

ITI Introduction to Computing II

Programming overview

Java Programming Training for Experienced Programmers (5 Days)

JAVA: A Primer. By: Amrita Rajagopal

Programming in C# Inheritance and Polymorphism

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

ITI Introduction to Computing II

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

9 Working with the Java Class Library

Concepts of Programming Languages

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

Chapter 6 Introduction to Defining Classes

Inheritance (Part 5) Odds and ends

CS-202 Introduction to Object Oriented Programming

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

What is Inheritance?

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Classes, subclasses, subtyping

Comp 249 Programming Methodology

CMSC 132: Object-Oriented Programming II

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Building custom components IAT351

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

CS11 Introduction to C++ Fall Lecture 7

Programming II (CS300)

Advanced Placement Computer Science. Inheritance and Polymorphism

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Methods Common to all Classes

Interview Questions of C++

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Chapter 5 Object-Oriented Programming

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

OVERRIDING. 7/11/2015 Budditha Hettige 82

More on Inheritance. Interfaces & Abstract Classes

Chapter 2: Java OO II X I A N G Z H A N G

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Distributed Systems Recitation 1. Tamim Jabban

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Programming Languages 2nd edition Tucker and Noonan"

Computer Science II (20073) Week 1: Review and Inheritance

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

EEE-425 Programming Languages (2013) 1

Inheritance, polymorphism, interfaces

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

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

CS 251 Intermediate Programming Inheritance

Chapter 4 Defining Classes I

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Objects and Iterators

Compaq Interview Questions And Answers

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Inheritance (continued) Inheritance

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

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

More on Objects in JAVA TM

Transcription:

Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction in a structured way Systems Thinking System is: any part of anything that you want to think about as an indivisible unit Interface is: a description of the boundary between a system and everything else, that also explains how to think about that system as a unit Subsystem/component is: a system that is used inside, i.e., as a part of, another system (a relative notion!) Example: Ice/Water Dispenser Select water, crushed ice, or cubed ice. Place a glass against the pad and push. People's Roles wrt Systems Client is: a person (or a role played by some agent) viewing a system from the outside as an indivisible unit Implementer is: a person (or a role played by some agent) viewing a system from the inside as an assembly of subsystems/components Interfaces: Describing Behavior Information hiding is: a technique where you intentionally leave out information that is merely an internal implementation detail of the system Abstraction is: a complementary technique where you create a valid cover story to mask the effects of hiding (presumably important) information about internal implementation details 1

Basic Concepts of OO Object Interface Class Component Attribute Package Operation Relationship What is an Object? Informally, an object represents a real-world entity - physical, conceptual, or software Formally, an object is a concept or abstraction with sharp boundaries and meaning in an application Includes state, identity, and behavior State, Identity, and Behavior State Current values of attributes Changes over lifetime of object Identity Unique identity; state may be same at a particular instant Behavior Determines how an object responds to external environment What is a Class? A class is a blueprint for creating instances that have certain attributes Everything that is associated with a class is inside it All objects created by instantiating that class have all these attributes and functionality Object-Oriented Design involves breaking a problem down into units of responsibility. Each such unit knows all about itself, and how to manage itself. Classes define such units of responsibility The responsibilities of a class are defined by its methods Class: Syntax Java public class HelloWorld C# public class HelloWorld <<class>> ClassName Data members Each method defines a certain responsibility of a class Example: In a card game, Deck would be a class. The state of the Deck would be all the cards that are currently in it (not dealt). Its responsibilities would be to deal and to shuffle cards. Declaring. A method declaration is composed of a header and a block or body The header defines the signature of the method (identification) The various parts of the header are: Modifiers - public, private, protected, static, final, abstract Result Type - void, primitive data type, or class type Name of method Parameters (optional) Example: public intcalcsum(intx1, intx2) 2

Types of Constructor. Create new instance of class Transformer. Change state of an object Observer. Retrieve information about state of an object Copy Constructor. Create new instance of class, and copy some or all of the state of the current object Iterator. Process one at a time all the data of an object Example: A Stack Class public class BStackOfInt intnelems; intelems[10]; public BStackOfInt() nelems= 0; public void push(intx) elems[nelems++] = x; public intpop() int x = elems[nelems-1]; numelems--; return x; public inttop() return elems[nelems-1]; public intlength() return nelems; Example: Using Stack StackOfInt s1 = new StackOfInt(); int x = 5; int y = 7; s1.push(x); s1.push(y); int z = s1.length(); x = s1.pop(); y = s1.pop(); z = s1.length(); Interfaces Abstract component Includes only method signatures No state (data members) Cannot be instantiated <<interface>> InterfaceName A class implements one (or more) interface Class must provide bodies for all methods in interface Interface: Syntax Implementing Interfaces public interface IStackOfInt void Push(int x); int Pop(); int Top(); int Length(); public interface IStackOfInt void Push(int x); int Pop(); int Top(); int Length(); public class BStackOfInt implements IStackOfInt public class BStackOfInt : IStackOfInt <<interface>> IStackOfInt All methods in an interface are public by default <<class>> BStackOfInt <<class>> UStackOfInt 3

Inheritance Inheritance is the mechanism by which one class can acquire properties/responsibilities of another class If your application is going to include a bunch of classes that are related, and have a lot in common, then a good way of designing these classes is to put all the common properties and responsibilities in a single base class Individual classes inherit commonalities from the base class Each of the classes that inherit from a base class is called a derived class or a subclass Inheritance: Example Employee Manager Accountant Janitor Engineer Inheritance: Syntax public class BRevStackOfInt extends BStackOfInt <<class>> BStackOfInt public class BRevStackOfInt : BStackOfInt <<class>> BRevStackOfInt Assignment Compatibility All objects of subclasses can be stored in variables of their own types, as well as their superclass type You can always go from a specialized type to a more general type but not the other way around Employee e = new Employee(); Manager m = new Manager(); Accountant a = new Accountant(); Employee e1 = new Janitor(); // Can store a Janitor object in an // Employee reference Janitor j = new Employee(); // error // Reverse is not possible Class Hierarchy Inheritance relationships establish a class hierarchy among the classes in the system At the root of all class hierarchies is the Object (object) class Every class is by default a subclass of the Object (object) class What does this mean in terms of assignment compatibility? this and super this: a reference to the object to which the method belongs super: a reference to the object s immediate superclass, if any; undefined otherwise public class BaseClass protected int someint; public void SomeMethod() this.someint = this.someint * 2; // Other methods public class DerivedClass extends BaseClass public void SomeMethod() super.somemethod(); this.someint = this.someint * 2; public void AnotherMethod() // something happens 4

Typecasting public class BaseClass protected int someint; public void SomeMethod() System.out.println( BC ); // Other methods public class DerivedClass extends BaseClass public void SomeMethod() super.somemethod(); System.out.println( DC ); public void AnotherMethod() // something happens public class ClassTester public static void main(string a[]) BaseClass b = new BaseClass(); DerivedClass d = new DerivedClass(); b = d; // Changes the dynamic type // of d to BaseClass (upcasting) d = b; // Error: downcasting is not // allowed. d = (DerivedClass) b; // Explicit casting: OK, but // dangerous Polymorphism public class BaseClass protected int someint; public void SomeMethod() System.out.println( BC ); // Other methods public class DerivedClass extends BaseClass public void SomeMethod() super.somemethod(); System.out.println( DC ); public void AnotherMethod() // something happens public class ClassTester public static void main(string a[]) BaseClass b = new BaseClass(); DerivedClass d = new DerivedClass(); b.somemethod(); b = d; // Changes the dynamic type // of d to BaseClass // (upcasting) b.somemethod(); Static and Dynamic Type Static type assigned by declaration BaseClass b = new BaseClass(); DerivedClass d = new DerivedClass(); Dynamic type assigned by assignment b = d; Function tables The Object Class Root of the class hierarchy Includes methods to perform basic functions clone, equals, finalize, getclass, hashcode, tostring, notify, notifyall, wait These methods can be invoked on any object of any class Interface Inheritance Inheritance applies to interfaces as well Syntax: public interface DerivedInt extends BaseInt public interface DerivedInt : BaseInt <<interface>> BaseInt <<interface>> DerivedInt Multiple Inheritance Can a single class have more than one parent? C# and Java disallow multiple class inheritance Use interfaces instead Why does this not have the same problem? 5

static Members and Belong to all instances of a class Don t need an instance of class to use A change to a static member affects all instances Rules for Using static Neither reads from nor writes to instance fields Independent of the state of the object Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value Factory methods that serve in lieu of constructors Packages/Namespaces Grouping sets of related classes (or interfaces) To use a package/namespace, you need to import (use) it package 625Samples; // class definition Client program file: import 625Samples.*; namespace 625Samples // class definition Client program file: using 625Samples; Packages/Namespaces Java Packages Correspond to the file system Each directory is a package Classes in a package must be defined in a file in the correct directory C# Namespaces Files can be located anywhere Grouping is based only on the name of the namespace defined Class Libraries Both Java and C# provide a very rich set of standard classes I/O, graphics, remoting, utilities, database support, XML support, math functions, etc. Just import the package/class you want to use and use it Code reuse java.lang.* is automatically imported Exceptions Something bad happened! Rather than crashing (or core dump), Java/C# programs throw an exception Somebody has to catch this exception Syntax try catch finally The Java throws keyword 6

Handling Exceptions Fix the problem and try again Do something else instead Exit the application with System.exit() Rethrow the exception Throw a new exception Return a default value (in a non-void method) Eat the exception and return from the method (in a void method) Eat the exception and continue in the same method (Rare and dangerous) Exception Hierarchy The Exception class is the root of the exception hierarchy User-defined exceptions Your program can define specific kinds of exceptions Your exceptions must extend Exception Cloning Cloneable interface Deep vs. shallow copy Overloading Same method name with different sets of parameters Overloading just based on return type is not allowed Operator overloading Not allowed in Java/C# Collection Classes Lists, Stacks, Queues, etc. Part of class library Genericity Being able to define a generic component, and allowing the client to specialize it C++ templates, Java 1.5 generics, C# 2.0 generics Resources Java http://java.sun.com http://www.javaworld.com Eclipse IDE -- http://www.eclipse.org C# http://www.msdn.microsoft.com/vcsharp www.c-sharpcorner.com Visual Studio.NET 7