ICS 4U. Introduction to Programming in Java. Chapter 10 Notes

Similar documents
Chapter 10 Classes Continued. Fundamentals of Java

Chapter 3: Inheritance and Polymorphism

Introduction to Programming Using Java (98-388)

TWO-DIMENSIONAL FIGURES

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

ITI Introduction to Computing II

ITI Introduction to Computing II

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

OBJECT ORİENTATİON ENCAPSULATİON

Inheritance. COMP Week 12

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction

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

Java Object Oriented Design. CSC207 Fall 2014

Making New instances of Classes

Solution Notes. COMP 151: Terms Test

The Nervous Shapes Example

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

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

G Programming Languages - Fall 2012

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Programming overview

COP 3330 Final Exam Review

INHERITANCE AND EXTENDING CLASSES

CS1150 Principles of Computer Science Objects and Classes

Chapter 14 Abstract Classes and Interfaces

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CMSC 132: Object-Oriented Programming II

Inheritance and Polymorphism

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Has-a Relationships. A pen has a or contains a ball

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

PROGRAMMING LANGUAGE 2

Chapter 6 Introduction to Defining Classes

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

Inheritance (cont.) Inheritance. Hierarchy of Classes. Inheritance (cont.)

Introduction to Design Patterns

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

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

F I N A L E X A M I N A T I O N

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

Object typing and subtypes

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Inheritance. Transitivity

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

2. The object-oriented paradigm

CS260 Intro to Java & Android 03.Java Language Basics

Object-Oriented Programming Concepts

15CS45 : OBJECT ORIENTED CONCEPTS

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Using Inheritance to Share Implementations

Java Fundamentals (II)

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

ITI Introduction to Computing II

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

ITI Introduction to Computing II

+ Questions about Assignment 5?

Declarations and Access Control SCJP tips

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

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

Chapter - 2: Geometry and Line Generations

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Programming Languages and Techniques (CIS120)

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

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

QUESTIONS FOR AVERAGE BLOOMERS

Week 9. Abstract Classes

8359 Object-oriented Programming with Java, Part 2. Stephen Pipes IBM Hursley Park Labs, United Kingdom

2. The object-oriented paradigm!

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

index.pdf January 21,

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

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

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

Inheritance and Polymorphism

CS 251 Intermediate Programming Inheritance

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

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

Inheritance and Polymorphism

CSCE3193: Programming Paradigms

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

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

What is Inheritance?

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

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

Data Abstraction. Hwansoo Han

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

CH. 2 OBJECT-ORIENTED PROGRAMMING

Get Unique study materials from

5.6.1 The Special Variable this

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Reviewing OO Concepts

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

INHERITANCE - Part 1. CSC 330 OO Software Design 1

CST242 Object-Oriented Programming Page 1

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

INHERITANCE - Part 1. CSC 330 OO Software Design 1

Transcription:

ICS 4U Introduction to Programming in Java Chapter 10 Notes Classes and Inheritance In Java all programs are classes, but not all classes are programs. A standalone application is a class that contains a main method, and may, or may not, contain other methods. An applet is a class that extends the class Applet. It contains a number of standard methods including a paint method. Neither one of these two classes is used as a template to create objects. In this chapter we look at the more general idea of a class, how objects are instantiated from it and how new classes can be produced from it by inheritance. 10.1 Objects and Abstract Data Types As programs become larger, controlling interference between parts becomes more difficult. Interference can be minimized by isolating all methods that share common variables and encapsulating them in an object, along with the shared variables. When this is done, no other part of a program needs to be concerned with how the data is stored in the object. Only those methods inside the object are involved. In this sense the data is abstracted and we speak of the whole as an abstract data type or ADT. Of course, one object in a program must communicate with other objects or it would not be a single program, just a group of separate, smaller programs. This communication occurs when one object uses methods of another object. This is known as message passing. For any object to use a method encapsulated in another object, several things are necessary. The object using another object s method must have imported the other class to which the other object belongs either explicitly or implicitly. The method that is used must have been declared public. In Java, objects are instantiated from classes which act as templates for their creation. Whenever changes are made in the way an object stores data or the way that its methods are implemented, assuming their signatures and what they accomplish remain unchanged, other objects using objects instantiated from the class need not be altered. By this means, unwanted interference between objects in a larger program can be prevented, without having to keep each class unchanged. 10.2 Using a Class We will begin by looking at an object instantiated from a class from the outside, as any other object or main method using it would, and see how it can be used. For example, consider a class called Turtle that can be used to instantiate objects to produce line drawings. To visualize the object, think of a turtle that is set at a certain position on the screen and pointed in a certain direction. As the turtle moves, it traces a line on the screen. It always moves in a straight

line unless its direction is changed. It can turn a certain angle to its left or to its right. It can also move without leaving a trace. Here is the list of the public methods of the Turtle class with their signatures. These angles are in degrees and measured in a counterclockwise direction from a horizontal line pointing right, just as they are in mathematics. Signature setcolor(color clr) setposition(int x, int y) setangle(int angle) move(int distance) turnleft(int angle) turnright(int angle) showtrace() hidetrace() Behariour Set colour of trace. Place turtle at (x,y). Point turtle at angle to horizontal. Move distance in pointing direction. Turn angle to turtle s left from present pointing direction. Turn angle to turtle s right from present pointing direction. Cause trace to show. Stop trace from showing. Sample Turtle Classes (NOTE: import hsa.book.*; contains the Turtle class) // The "RedSquare" class. // Draw a red square of size 30 pixels with its upper-left corner // at the center of console window. // Instantiate object t and set color. import java.awt.*; import hsa.book.*; public class RedSquare static Console c; // The output console public static void main (String [] args) Turtle t; t = new Turtle (c); t.setcolor (Color.red); t.move (30); // Draw first side. t.move (30); // Draw second side. t.move (30); // Draw third side. t.move (30); // Draw fourth side. // main method // RedSquare class or

public static void main (String [] args) Turtle t; t = new Turtle (c); t.setcolor (Color.red); // uses a loop to make the square for (int side = 1 ; side <= 4 ; side++) t.move (30); // The "DrawMoon" class. // Draws a moon at center of console window // of radius 60 pixels and color green. import java.awt.*; import hsa.book.*; public class DrawMoon static Console c; // The output console public static void main (String [] args) Turtle t; t = new Turtle (c); t.setcolor (Color.green); for (int square = 1 ; square <= 36 ; square++) for (int side = 1 ; side <= 4 ; side++) t.move (60); t.turnright (10); // main method // DrawMoon class 10.3 Creating the Turtle Class We will now look at how the Turtle class itself is implemented. Using the class requires no knowledge of its implementation. The instantiated class encapsulates both data and methods. Methods that are to be available to be used by other objects are labeled public. The data and methods used only by other methods of the class are labeled protected. The data (or instance variables) record the current position of the turtle, the direction that it is pointing, its current color, and whether or not the trace is currently showing. Look at pages 255-256 for the Turtle class to see the protected data. 10.4 Instantiating Two Objects from a Class

Here is a main method that uses two turtles to draw two spirals, one in orange and the other in cyan. Each spiral begins at the center of the screen but the orange turns to the right, and the cyan to the left. // The "DrawMoon" class. // Draws a moon at center of console window // of radius 60 pixels and color green. import java.awt.*; import hsa.book.*; public class DrawMoon static Console c; // The output console public static void main (String [] args) Turtle t; t = new Turtle (c); t.setcolor (Color.green); for (int square = 1 ; square <= 36 ; square++) for (int side = 1 ; side <= 4 ; side++) t.move (60); t.turnright (10); // main method // DrawMoon class TO DO: Try the sample programs on these pages. Answer Questions #1 and #2 on page 268.

Chapter 10 Notes continued 10.5 Method Overloading In the Turtle class definition there are two methods named Turtle. These are each constructor methods. When a turtle object is instantiated using the constructor with one parameter, as by Turtle(Console c), the first version is used. The turtle is set to the default position of the center of the screen, pointing to the right. The second version has, as well, parameters for the coordinates of the starting position and starting angle. This allows the user to begin drawing at another point in the window and pointing in another direction. In either case the turtle is set to showing the trace and drawing in black. In the second version of the constructor there must be a distinction between the parameters of the constructor x and y, and angle and the class variables x, y, and angle. To differentiate them, the keyword this identifies the variables that belong to the object itself. Thus the statement this.x = x; assigns to the instance variable x the value of the parameter x. When two or more methods have the same identifier, as the two versions of the constructor method Turtle have here, we say the method is overloaded. Which version is to be used depends on the parameters provided. It is possible to have methods of a class other than the constructor method overloaded but this is not done. Many classes in the Java library provide a variety of constructor methods. No two of these can have the same number and data type of parameters of they could not be distinguished from one another. If no constructor method is provided for a class, the initial values of instance variables are automatically default values. 10.6 Creating a New Class by Inheritance It is possible to create a new class based on an old one by modifying it in various ways. New methods can be added or existing methods changed. We will change the class Turtle by allowing control of the width of the line that is traced by the turtle. This means we must add an additional class variable called linewidth that can be changed from its default value of 1 pixel by the operation setlinewidth (int width) where width is the new line width. We must also change the existing method move to draw a line of the proper width. It, in turn, will use a new method that is added, but not made public, called drawfatline. This method creates a fat line by drawing a ball of radius half the line width points along the line, close enough together to create the effect of a solid line, somewhat like a ballpoint pen. Here is the new class.

// The "FatTurtle" class. // For drawing graphics with a variety of line widths. // This class extends the Turtle class. import hsa.book.*; public class FatTurtle extends Turtle // Add a new variable. protected int linewidth; // Only one version of constructor provided. public FatTurtle (Console c) super (c); // Use default setting for other variables defined in Turtle class. linewidth = 1; // FatTurtle constructor // Add a new method to set LineWidth. public void setlinewidth (int newwidth) linewidth = newwidth; // setlinewidth method // Draw a filled ball of radius and center at (x, y) // in the current color. protected void drawball (int xc, int yc, int radius) int diameter = radius * 2; int x = xc - radius; int y = yc - radius; c.filloval (x, y, diameter, diameter); // drawball method // Add method drawfatline. protected void drawfatline (int x1, int y1, int x2, int y2) // Line drawn by moving a ball point pen whose ball // is half line width. // Line drawn at x values of ball separated by DX which // is half the radius. // Constants used in calculation. final double LEN = Math.sqrt (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); final double SINA = (y2 - y1) / LEN; final double COSA = (x2 - x1) / LEN; final int RADIUS = (linewidth / 2) + 1; final double DX = RADIUS * COSA / 2; final double DY = RADIUS * SINA / 2; // Set position to draw first ball's center at (x1, y1). double xpos = x1; double ypos = y1; // Draw series of balls along line from (x1, y1) to (x2, y2). do

drawball ((int) Math.round (xpos), (int) Math.round (ypos), RADIUS); xpos += DX; ypos += DY; while (Math.sqrt ((x2 - xpos) * (x2 - xpos) + (y2 - ypos) * (y2 - ypos)) >= RADIUS / 2); // drawfatline method // This method overrides the move method of the Turtle class. public void move (int distance) double rangle = angle * Math.PI / 180; final int newx = (int) Math.round (x + Math.cos (rangle) * distance); final int newy = (int) Math.round (y + Math.sin (rangle) * distance); if (showing) c.setcolor (clr); if (linewidth == 1) c.drawline (x, y, newx, newy); else drawfatline (x, y, newx, newy); x = newx; y = newy; // move method /* FatTurtle class */ Notice that it is not necessary to repeat the methods of Turtle that are unchanged. The only new variable added is linewidth. The new method made public is setlinewidth. The new method move overrides (replaces) the old version of move. If the width is given as 1 pixel, the Console method drawline is used. If the width has been set at another value then the new method drawfatline is used. Using the Modified Class Here is a main method that uses the FatTurtle class to draw concentric fat circles with centers at the center of the window. The circles will each be made up of 36 short straight lines. A yellow circle will have a radius of getwidth/6 and linewidth of 10 and a green circle radius getwidth/4 and linewidth of 20 pixels. // The "FatCircles" class. // Use FatTurtle class to draw concentric circles. import java.awt.*; public class FatCircles static Console c; // The output console public static void main (String [] args) FatTurtle turtle1, turtle2;

turtle1 = new FatTurtle (c); turtle2 = new FatTurtle (c); turtle1.setlinewidth (10); turtle2.setlinewidth (20); turtle1.setcolor (Color.yellow); turtle2.setcolor (Color.green); // Set the x position of each turtle at its own radius from the center // of the window pointing up. // Compute some constants. final int XC = c.getwidth () / 2; final int YC = c.getheight () / 2; final int RADIUS1 = c.getwidth () / 6; final int RADIUS2 = c.getwidth () / 4; final int STEPANGLE = 10; final double STEPANGLERADIANS = STEPANGLE * 2 * Math.PI / 360; final int DISTANCE1 = (int) Math.round (RADIUS1 * STEPANGLERADIANS); final int DISTANCE2 = (int) Math.round (RADIUS2 * STEPANGLERADIANS); turtle1.setposition (XC + RADIUS1, YC - DISTANCE1 / 2); turtle2.setposition (XC + RADIUS2, YC - DISTANCE2 / 2); turtle1.turnleft (90); turtle2.turnleft (90); for (int direction = 0 ; direction <= 360 ; direction += STEPANGLE) turtle1.move (DISTANCE1); turtle1.turnleft (STEPANGLE); turtle2.move (DISTANCE2); turtle2.turnleft (STEPANGLE); // main method // FatCircles class 10.7 Class Heirarchy When one class extends another class the parent of base class is called the superclass; the one that inherits from it is the subclass. A subclass may not inherit any variables or methods of the superclass that are labeled as private. But it may inherit any labelled as protected. That is why we have labeled so many of the variables as protected. They cannot be used by another class outside the hierarchy in either case. An object of a subclass is an object of the superclass. But the reverse is not true. The object of a superclass in not an object of the subclass. Structured Java data types such as strings and arrays are objects, as are those that we create such as record types or node types for a linked list. They are used by reference. All these classes are extensions of the superclass Object. It is thus possible, for example, to create a List class for maintaining a list that has data of type Object. Since all non-primitive data types are Objects the same List class could be used for many different structured data types. There exist, as well, a number of classes called type wrapper classes, one for each of the primitive data types: Integer for int, Float for float, Boolean for boolean, and so on. In this way primitive data types can be adapted to a class written for Objects. TO DO: Try the sample programs on these pages. Answer Questions #3, #4, #5, #6 and #7 on page 269-270.