CMSC 132: Object-Oriented Programming II

Similar documents
CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II. Generic Programming. Department of Computer Science University of Maryland, College Park

Programming II (CS300)

Java Object Oriented Design. CSC207 Fall 2014

Chapter 10 Classes Continued. Fundamentals of Java

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

Chapter 6 Introduction to Defining Classes

Programming II (CS300)

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CPS 506 Comparative Programming Languages. Programming Language

Inheritance and Polymorphism

Class, Variable, Constructor, Object, Method Questions

Object Oriented Programming. Java-Lecture 11 Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Programming overview

ITI Introduction to Computing II

Data Abstraction. Hwansoo Han

CS-202 Introduction to Object Oriented Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

ITI Introduction to Computing II

OBJECT ORİENTATİON ENCAPSULATİON

Chapter 14 Abstract Classes and Interfaces

Inheritance and Interfaces

Inheritance, and Polymorphism.

INHERITANCE. Spring 2019

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

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

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.

Java: introduction to object-oriented features

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Object-Oriented Programming

1 Shyam sir JAVA Notes

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

CS 251 Intermediate Programming Inheritance

C++ (classes) Hwansoo Han

CH. 2 OBJECT-ORIENTED PROGRAMMING

CLASSES AND OBJECTS IN JAVA

More C++ : Vectors, Classes, Inheritance, Templates

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

Chapter 5 Object-Oriented Programming

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

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

PROGRAMMING LANGUAGE 2

CS260 Intro to Java & Android 03.Java Language Basics

Practice for Chapter 11

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

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Object-oriented Programming. Object-oriented Programming

C10: Garbage Collection and Constructors

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

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

Data Structures (list, dictionary, tuples, sets, strings)

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Properties of an identifier (and the object it represents) may be set at

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

Compaq Interview Questions And Answers

Self-review Questions

Inheritance, Polymorphism, and Interfaces

Chapter 11 Classes Continued

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Generalized Code. Fall 2011 (Honors) 2

7. C++ Class and Object

Module 10 Inheritance, Virtual Functions, and Polymorphism

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

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Lecture 5: Inheritance

What about Object-Oriented Languages?

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance?

JAVA MOCK TEST JAVA MOCK TEST II

CSE 307: Principles of Programming Languages

Building Multitier Programs with Classes

Chapter 4 Java Language Fundamentals

INHERITANCE - Part 1. CSC 330 OO Software Design 1

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

Testing Object-Oriented Software. COMP 4004 Fall Notes Adapted from Dr. A. Williams

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

Inheritance and Polymorphism

Inheritance. Transitivity

And Even More and More C++ Fundamentals of Computer Science

Making New instances of Classes

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

The Essence of OOP using Java, Nested Top-Level Classes. Preface

CST141--Inheritance 2

Declarations and Access Control SCJP tips

20 Most Important Java Programming Interview Questions. Powered by

Advanced Programming Using Visual Basic 2008

Inheritance Motivation

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Transcription:

CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park

Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation Abstract Data Type (ADT) Implementation independent interfaces Data and operations on data Java Many language features supporting OOP

Overview Objects & class, this, super References, alias, levels of copying Constructor, initialization block Garbage collection, destructor Package, scope, inner classes Modifiers Public, Private, Protected Static, Final, Abstract Generic programming

Object & Class Object Abstracts away (data, algorithm) details Encapsulates data Instances exist at run time Class Blueprint for objects (of same type) Exists at compile time

this Reference Description Reserved keyword Refers to object through which method was invoked Allows object to refer to itself Use to refer to instance variables of object

this Reference Example class Node { value val1; value val2; void foo(value val2) { = val1; // same as this.val1 (implicit this) = val2; // parameter to method = this.val2; // instance variable for object bar( this ); // passes reference to object

Inheritance Definition Relationship between classes when state and behavior of one class is a subset of another class Terminology Superclass / parent More general class Subclass More specialized class Forms a class hierarchy Helps promote code reuse

Description Reserved keyword super Reference Refers to superclass Allows object to refer to methods / variables in superclass Examples super.x super() super.foo() // accesses variable x in superclass // invokes constructor in superclass // invokes method foo() in superclass

Reference References & Aliases A way to get to an object, not the object itself All variables in Java are references to objects Alias Multiple references to same object x == y operator tests for alias x.equals(y) tests contents of object (potentially) Reference x Reference y Object z

Cloning Cloning Creates identical copy of object using clone( ) Cloneable interface Supports clone( ) method Returns copy of object Copies all of its fields Does not clone its fields Makes a shallow copy

Three Levels of Copying Objects Assume y refers to object z 1. Reference copy Makes copy of reference x = y; 2. Shallow copy Makes copy of object x = y.clone( ); 3. Deep copy Makes copy of object z and all objects (directly or indirectly) referred to by z y x y x y x z z z' z z'

Constructor Description Method invoked when object is instantiated Helps initialize object Method with same name as class w/o return type Default parameterless constructor If no other constructor specified Initializes all fields to 0 or null Implicitly invokes constructor for superclass If not explicitly included

Constructor Example class Foo { Foo( ) { // constructor for Foo class Bar extends Foo { Bar( ) { // constructor for Bar // implicitly invokes Foo( ) here class Bar2 extends Foo { Bar2( ) { // constructor for bar super(); // explicitly invokes Foo( ) here

Initialization Block Definition Block of code used to initialize static & instance variables for class Motivation Enable complex initializations for static variables Control flow Exceptions Share code between multiple constructors for same class

Initialization Block Types Static initialization block Code executed when class loaded Initialization block Code executed when each object created (at beginning of call to constructor) Example class Foo { static { A = 1; // static initialization block { A = 2; // initialization block

Variable Initialization Variables may be initialized At time of declaration In initialization block In constructor Order of initialization 1. Declaration, initialization block (in the same order as in the class definition) 2. Constructor

Variable Initialization Example class Foo { static { A = 1; // static initialization block static int A = 2; // static variable declaration static { A = 3; // static initialization block { B = 4; // initialization block private int B = 5; // instance variable declaration { B = 6; // initialization block Foo() { // constructor A = 7; B = 8; // now A = 7, B = 8 // initializations executed in order of number

Garbage Collection Concepts All interactions with objects occur through reference variables If no reference to object exists, object becomes garbage (useless, no longer affects program) Garbage collection Reclaiming memory used by unreferenced objects Periodically performed by Java Not guaranteed to occur Only needed if running low on memory

Description Destructor Method with name finalize() Returns void Contains action performed when object is freed Invoked automatically by garbage collector Not invoked if garbage collection does not occur Usually needed only for non-java methods Example class Foo { void finalize() { // destructor for foo

Description Method Overloading Same name refers to multiple methods Sources of overloading Multiple methods with different parameters Constructors frequently overloaded Redefine method in subclass Example class Foo { Foo( ) { // 1 st constructor for Foo Foo(int n) { // 2 nd constructor for Foo

Package Definition Group related classes under one name Helps manage software complexity Separate namespace for each package Package name added in front of actual name Put generic / utility classes in packages Avoid code duplication Example package edu.umd.cs; // name of package

Package Import Import Make classes from package available for use Java API java.* (core) javax.* (optional) Example import java.util.random; // import single class import java.util.*; // all classes in package // class definitions

Scope Scope Part of program where a variable may be referenced Determined by location of variable declaration Boundary usually demarcated by { Example public MyMethod1() { int myvar; myvar accessible in... method between {

Class Method Class Package Method Scope Example Example package edu.umd.cs ; public class MyClass1 { public void MyMethod1() {... public void MyMethod2() {... public class MyClass2 { Scopes

Inner Classes Description Class defined in scope of another class Property Can directly access all variables & methods of enclosing class (including private fields & methods) Example public class OuterClass { private Object value; public class InnerClass {...Object x = value;

Modifier Description Java keyword (added to definition) Specifies characteristics of a language construct (Partial) list of modifiers Public / private / protected Static Final Abstract

Modifier Examples public class Foo { private static int count; private final int increment = 5; protected void finalize { public abstract class Bar { abstract int go( ) {

Visibility Modifier Properties Controls access to class members Applied to instance variables & methods Four types of access in Java Public Protected Package Default if no modifier specified Private Most visible Least visible

Visibility Modifier Where Visible public Referenced anywhere (i.e., outside package) protected Referenced within package, or by subclasses outside package None specified (package) Referenced only within package private Referenced only within class definition Applicable to class fields & methods

For instance variables Visibility Modifier Should usually be private to enforce encapsulation Sometimes may be protected for subclass access For methods Public methods provide services to clients Private methods provide support other methods Protected methods provide support for subclass

Static variable Modifier Static Single copy for class Shared among all objects of class Static method Can be invoked through class name Does not need to be invoked through object Can be used even if no objects of class exist Can not reference instance variables

Final variable Modifier Final Value can not be changed Must be initialized in every constructor Attempts to modify final are caught at compile time Final static variable Used for constants Example final static int Increment = 5;

Final method Modifier Final Method can not be overridden by subclass Private methods are implicitly final Final class Class can not be a superclass (extended) Methods in final class are implicitly final

Using final classes Modifier Final Prevents inheritance / polymorphism May be useful for Security Object oriented design Example class String is final Programs can depend on properties specified in Java library API Prevents subclass that may bypass security restrictions

Description Modifier Abstract Represents generic concept Just a placeholder Leave lower-level details to subclass Applied to Methods Classes Example abstract class Foo { abstract void bar( ) { // abstract class // abstract method

Abstract Motivating Example Graphics drawing program Define a base class Shape Derive various subclasses for specific shapes Each subclass defines its own method drawme( ) public class Shape { public void drawme( ) { // generic drawing method public class Circle extends Shape { public void drawme( ) { // draws a Circle public class Rectangle extends Shape { public void drawme( ) { // draws a Rectangle

Motivating Example Shapes Implementation shapes Picture consists of array shapes of type Shape[ ] To draw the picture, invoke drawme( ) for all shapes Shape[ ] shapes = new Shape[ ]; shapes[0] = new Circle( ); shapes[1] = new Rectangle( ); for ( int i = 0; i < shapes.length; i++ ) shapes[i].drawme( ); [0] [1] [2] Store the shapes to be drawn in an array. Draws all the shapes. Each call invokes drawme for the specific shape. (a Circle object) (a Rectangle object) Heap:

Motivating Example Shapes Problem Shape object does not represent a specific shape Since Shape is just a superclass How to implement Shape s drawme( ) method? public class Shape { void drawme( ) { // generic drawing method

Motivating Example Shapes Possible solutions Draw some special undefined shape Ignore the operation Issue an error message Throw an exception Better solution Abstract drawme( ) method, abstract Shape class Tells compiler Shape is incomplete class

Abstract Method Behaves much like method in interface Give a signature, but no body Includes modifier abstract in method signature Class descendents provide the implementation Abstract methods cannot be final Since must be overridden by descendent class Final would prevent this

Abstract Class Required if class contains any abstract method Includes modifier abstract in the class heading public abstract class Shape { An abstract class is incomplete Cannot be created using new Shape s = new Shape( ); // Illegal! But can create concrete shapes (Circle, Rectangle) and assign them to variables of type Shape Shape s = new Circle( );

Example Solution Shapes public abstract class Shape { private int color; Shape ( int c ) { color = c; public abstract void drawme( ); Base class Shape is abstract because it contains the abstract (undefined) method drawme( ). Derived class Circle is concrete because it defines drawme( ). public class Circle extends Shape { private double radius; public Circle( int c, double r ) { details omitted public void drawme( ) { Circle drawing code goes here public class Rectangle extends Shape { private double height; private double width; public Rectangle( int c, double h, double w ) { details omitted public void drawme( ) { Rectangle drawing code goes here Derived class Rectangle is concrete because it defines drawme( ). The code for drawing the shapes given earlier can now be applied.

Abstract methods Abstract Summary Method that contains no body Subclass provides actual implementation Abstract classes Required if any method in class is abstract Can contain non-abstract methods Can be partial description of class

Generic Programming Generic programming Defining constructs that can be used with different data types I.e., using same code for different data types Implemented in Java through 1. Inheritance A extends B 2. Type variables <A>

Generic Programming Examples Inheritance Class A { dowork( A x ) { Class B extends A { A w1 = new A( ); B w2 = new B( ); w1.dowork( w1 ); w2.dowork( w2 ); Type Variables Class W<T> { dowork( T x ) { Class A { Class B { W<A> x1 = new W<A>( ); W<B> x2 = new W<B>( ); A w1 = new A( ); B w2 = new B( ); dowork( ) applied to objects of both class A and B x1.dowork( w1 ); x2.dowork( w2 );

Generic Class Class with one or more type variables Example class ArrayList<E> To use generic class, provide an actual type Valid types Class Interface Invalid types Primitive type (use wrappers) ArrayList<String> ArrayList<Comparable> ArrayList<int> ArrayList<Integer>

Defining a Generic Class Append type variable(s) to class name Use angle brackets ClassName<type variable> Can use any name for type variable But typically single uppercase letter T, E, etc Use the type variable to define Type of variables Type of method parameters Method return type Object allocation

Example Example Generic Class public class mygeneric<t> { private T value; public mygeneric( T v ) { value = v; public T getval( ) { return value; public void setval( T newv ) { value = newv;