Making New instances of Classes

Similar documents
Overview of the lecture. Some key issues in programming Java programming. CMPT Data and Program Abstraction. Some of the key programming issues

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

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

ITI Introduction to Computing II

Inheritance and Polymorphism

ITI Introduction to Computing II

Java Object Oriented Design. CSC207 Fall 2014

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Methods Common to all Classes

CS-202 Introduction to Object Oriented Programming

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Inheritance Motivation

Chapter 9 - Object-Oriented Programming: Inheritance

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

Inheritance and Polymorphism

Java Magistère BFA

INHERITANCE AND EXTENDING CLASSES

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

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

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

Chapter 9 - Object-Oriented Programming: Polymorphism

Rules and syntax for inheritance. The boring stuff

Reusing Classes. Hendrik Speleers

Object Oriented Programming. Java-Lecture 11 Polymorphism

Programming Exercise 14: Inheritance and Polymorphism

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

ITI Introduction to Computing II

Polymorphism. return a.doublevalue() + b.doublevalue();

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

ITI Introduction to Computing II

Inheritance (Deitel chapter 9)

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

index.pdf January 21,

INHERITANCE. Spring 2019

Chapter 6 Introduction to Defining Classes

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

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

OBJECT ORİENTATİON ENCAPSULATİON

Part 11 Object Oriented Programming: Inheritance

Inheritance (continued) Inheritance

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

CS 11 java track: lecture 3

CMSC 132: Object-Oriented Programming II

CS1150 Principles of Computer Science Objects and Classes

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

Exception-Handling Overview

Programming Languages and Techniques (CIS120)

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Java Fundamentals (II)

PROGRAMMING LANGUAGE 2

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

Inheritance (Part 5) Odds and ends

CMSC 132: Object-Oriented Programming II

Introduction to Programming Using Java (98-388)

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

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

Use the scantron sheet to enter the answer to questions (pages 1-6)

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

Programming 2. Inheritance & Polymorphism

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

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

CLASS DESIGN. Objectives MODULE 4

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Inheritance -- Introduction

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Chapter 4 Defining Classes I

Lecture 4: Extending Classes. Concept

CS260 Intro to Java & Android 03.Java Language Basics

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Inheritance and Interfaces

ITI Introduction to Computing II

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Practice for Chapter 11

Class, Variable, Constructor, Object, Method Questions

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

Super-Classes and sub-classes

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

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

Lecture 16: Object Programming Languages

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

CIS 110: Introduction to computer programming

Lecture 10. Overriding & Casting About

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CO Java SE 8: Fundamentals

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

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

EKT472: Object Oriented Programming. Overloading and Overriding Method

Transcription:

Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using the new operator in Java Example public static void main() { int size = 1000; HashTable h; Foo myfoo = new Foo(); h = new HashTable(size);... January 24, 2003 Copyright 2003 by Bill Havens 1 of 22

Gotchas New continued Objects are not allocated automatically in Java (cf- C++) You must use the new operator explicitly to create each instance Example again: public static void main() { int size = 1000; HashTable h; Foo myfoo = new Foo(); System.out.println(myfoo) System.out.println(h) h = new HashTable(size); System.out.println(h)... // prints FooXXXXXXXX // prints null // prints HashTableXXXXXXXX January 24, 2003 Copyright 2003 by Bill Havens 2 of 22

Details All Object variables in Java are called Reference Variables More details in the next lecture Reference variables must be explicitly assigned instances of their class Arrays in Java Arrays are considered Objects in Java But with the familiar subscript syntax of C (example: x[i] = x[j]+1;) BUT you must create new instances of arrays explicitly Example: public static void main() { int size = 1000; int[] x = new int[size]; January 24, 2003 Copyright 2003 by Bill Havens 3 of 22

Making new instances of a class Constructors Classes represent ALL of their potential instances Need a method of constructing new instances from the class Special method with the same name as the class Can be heavily overloaded Default Constructor By default, Java provides a constructor with no arguments that does nothing Example: public foo() { Rule: if you need a different constructor then Java does not provide even the no arg constructor January 24, 2003 Copyright 2003 by Bill Havens 4 of 22

Example: class foo { private int n; protected double[] hist; private long width; // better! public foo( int nn ) { n = nn; hist = new double[nn]; What is the utility of a constructor? Constructors should be called Initializers Provide sometimes necessary initial states for each object instance Example above: variable n needs to have a starting value and the double[] needs to be created. January 24, 2003 Copyright 2003 by Bill Havens 5 of 22

Review Constructors Summarized Every class has at least one constructor Default constructor provided by Java has no arguments and does nothing Useful for constructing uninitialized instances of the class If your class instances need initial state or contain references to other objects then you need a custom constructor If you define a constructor, you must also define the null constructor Syntax: the form of the constructor public foo(<arg>,... ) where foo is the class name and the <arg>s define the constructor signature January 24, 2003 Copyright 2003 by Bill Havens 6 of 22

Introduction Inheritance Complex in other OOP languages but simplified in Java Inheritance is a fundamental concept in Object Programming. Complex objects (classes) can be expressed as refinements to more basic objects. Many classes can inherit the same basic behaviour from a common parent class. Supports code reuse in large systems. Supports well structured knowledge representation. Java supports single inheritance but with multiple interfaces More on Interface Classes later January 24, 2003 Copyright 2003 by Bill Havens 7 of 22

Basic Ideas: Classes can inherit members (both data and procedure) from another class (called its SuperClass) Every class has exactly one superclass (defaults to class Object) All public and protected members of the superclass are also members of the subclass. Inheritance is transitive Each instance of the subclass contains its own copies of the members from the superclass (but static members are NOT inherited) January 24, 2003 Copyright 2003 by Bill Havens 8 of 22

Example: Geometric Shapes Consider a graphics program for rendering geometric shapes. Every shape has a location (point) on the screen and a fill_pattern for colouring the object. There are many types of geometric objects (subclasses of shape). Each subclass has specific (more complex) behaviour than the parent class shape. BUT inherits basic behaviour from the parent class. Examples: circle and rectangle. How can we organize our knowledge hierarchy to use class hierarchy? January 24, 2003 Copyright 2003 by Bill Havens 9 of 22

Knowledge Hierarchy Subclass inheritance forms a hierarchy (called the class hierarchy) For single inheritance, the hierarchy is a tree. Example: Geometric Shape knowledge hierarchy Shape Subclass Circle Rectangle Subclass inherits ALL the members (variables and methods) of the parent class. May define additional members as necessary. January 24, 2003 Copyright 2003 by Bill Havens 10 of 22

abstract class Shape { protected point xy; protected int fill_pat; public Shape(); public Point getpoint(); public void setpoint(point);... abstract public float area(); abstract public void draw(); Example: Shape Class // location of shape // rendering fill pattern // constructor // return location of Shape // set location // area of any shape // render any shape Use of keyword protected means that members are NOT part of public interface but accessible to any subclass. Keyword abstract means that only the class protocol is described and NOT (all of) the method implementation January 24, 2003 Copyright 2003 by Bill Havens 11 of 22

class Circle extends Shape { protected double radius; Subclass Circle public Circle(float r) { super(); radius = r; // make a circle with radius r // make the superclass instance first public float getradius() { return radius; public void setradius(double r) { radius = r; public void draw() { draw something // draw defined in this class. public float area() { return Math.pi*radius*radius;... Creating a new Circle creates a new Shape as part of the derived class. January 24, 2003 Copyright 2003 by Bill Havens 12 of 22

Another Inheritance Example Example: redefined class Sphere from textbook NOTE: extends class Circle Note that a default constructor must be coded Any constructors in the superclass MUST be called first public class Sphere extends Circle { // default constructor public Sphere() { super(1.0); // unit sphere // custom constructor public Sphere(double initialradius) { super(initialradius); January 24, 2003 Copyright 2003 by Bill Havens 13 of 22

more Methods equals() predicate overrides method in class Object Illustrates instance-of predicate and type casting Type Casting Operator (<type>)<exp> changes type of <exp> to <type> public boolean equals(object rhs) { return ((rhs instanceof Sphere) && (radius == ((Sphere)rhs).radius)); Overrides setradius() in class Circle public void setradius(double newradius) { if (newradius >= 0.0) this.radius = radius; else throw new IllegalArgumentException( negative radius ); Accessor illustrates throwing exceptions and use of this variable NOTE: runtime exceptions need not be caught (more later) January 24, 2003 Copyright 2003 by Bill Havens 14 of 22

more Methods public double diameter() { return 2.0 * radius; Note inefficiency of diameter() call public double circumference() { return Math.PI * diameter(); public double area() { return 4.0 * Math.PI * radius * radius; Note inefficiency of Math.pow() call public double volume() { return (4.0*Math.PI * Math.pow(radius, 3.0)) / 3.0; January 24, 2003 Copyright 2003 by Bill Havens 15 of 22

Redefining the tostring() method from class Object // NOTE: replaces displaystatistics() from textbook public String tostring () { return "\nradius = " + radius() + "\ndiameter = " + diameter() + "\ncircumference = " + circumference() + "\narea = " + area() + "\nvolume = " + volume(); //end class Sphere NOTE: inefficient method calls Next we will consider extending this class again January 24, 2003 Copyright 2003 by Bill Havens 16 of 22

Class Ball More practice in inheritance in Java We need to model a ball for some computer game perhaps Reuse existing code from Sphere plus new operations Some methods will be overriden to provide more specialized behaviour I am really a sphere A Ball is a sphere plus more semantics January 24, 2003 Copyright 2003 by Bill Havens 17 of 22

Class Ball public class Ball extends Sphere { private String thename; // the ball's name // create a default ball with unit radius an unknown name public Ball() { setname("unknown"); Default constructor for Sphere will automatically be called // Creates a ball with specified radius and name public Ball(double initialradius, String initialname) { super(initialradius); setname(initialname); Note that we had to call super constructor explicitly More operations specific to Ball... January 24, 2003 Copyright 2003 by Bill Havens 18 of 22

more Methods for class Ball public boolean equals(object rhs) { return ((rhs instanceof Ball) && (radius == ((Ball)rhs).radius) && (thename.equals(((ball)rhs).thename); Overrides equals() defined in Sphere Simplified name comparison to use equals() in class String more Accessors made final (why?) public final String name() { return thename; public final void setname(string newname) { thename = newname; January 24, 2003 Copyright 2003 by Bill Havens 19 of 22

more Accessors Reset the ball to new radius and name Is this a good idea? Consider the equals() predicate public void resetball(double newradius, String newname) { setradius(newradius); setname(newname); What are the method calls for? Override the tostring() method in Sphere Note: not using displaystatistics() from textbook public String tostring() { return thename + super.tostring(); Reuse the tostring() method from Sphere via the super keyword // end Ball January 24, 2003 Copyright 2003 by Bill Havens 20 of 22

Inheritance in Class Ball Note: displaystatics() replaced via tostring() Ball inherits all data and methods from Sphere BUT Adds variable thename and Overrides method definitions for equals() and tostring() January 24, 2003 Copyright 2003 by Bill Havens 21 of 22

Runtime Method Dispatching public static void main() { Sphere s = new Sphere(); Ball b = new Ball(12.0, soccer ball ); System.out.println( my sphere is +s); System.out.println( my ball is +b); Sphere x = b; System.out.println( my other sphere is really a ball = +x); Which tostring() methods are called? Rule: Java determines the type of the object instance at runtime and invokes the method defined in the actual type of the class. Compare to C++ which uses the type of the variable at compile time (unless the method is declared virtual) January 24, 2003 Copyright 2003 by Bill Havens 22 of 22