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