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

Size: px
Start display at page:

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

Transcription

1 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 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 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

2 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

3 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 for the Turtle class to see the protected data Instantiating Two Objects from a Class

4 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.

5 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 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.

6 // 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

7 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;

8 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

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

Chapter 3: Inheritance and Polymorphism

Chapter 3: Inheritance and Polymorphism Chapter 3: Inheritance and Polymorphism Overview Inheritance is when a child class, or a subclass, inherits, or gets, all the data (properties) and methods from the parent class, or superclass. Just like

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

TWO-DIMENSIONAL FIGURES

TWO-DIMENSIONAL FIGURES TWO-DIMENSIONAL FIGURES Two-dimensional (D) figures can be rendered by a graphics context. Here are the Graphics methods for drawing draw common figures: java.awt.graphics Methods to Draw Lines, Rectangles

More information

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

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding Java Class Design Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Objectives Implement encapsulation Implement inheritance

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Inheritance. COMP Week 12

Inheritance. COMP Week 12 Inheritance COMP1400 - Week 12 Uno Game Consider the card game Uno: http://en.wikipedia.org/wiki/uno_(card_game) There are 6 kinds of cards: number cards draw two skip reverse wild wild draw four Game

More information

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

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction Class Interaction There are 3 types of class interaction. One

More information

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

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Making New instances of Classes

Making New instances of Classes 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

More information

Solution Notes. COMP 151: Terms Test

Solution Notes. COMP 151: Terms Test Family Name:.............................. Other Names:............................. ID Number:............................... Signature.................................. Solution Notes COMP 151: Terms

More information

The Nervous Shapes Example

The Nervous Shapes Example The Nervous Shapes Example This Example is taken from Dr. King s Java book 1 11.6 Abstract Classes Some classes are purely artificial, created solely so that subclasses can take advantage of inheritance.

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

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

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

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

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5 Objective Questions BCA Part III page 1 of 5 1. Java is purely object oriented and provides - a. Abstraction, inheritance b. Encapsulation, polymorphism c. Abstraction, polymorphism d. All of the above

More information

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using Java Provided Classes In this lesson we'll focus on using the Graphics class and its capabilities. This will serve two purposes: first

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

INHERITANCE AND EXTENDING CLASSES

INHERITANCE AND EXTENDING CLASSES INHERITANCE AND EXTENDING CLASSES Java programmers often take advantage of a feature of object-oriented programming called inheritance, which allows programmers to make one class an extension of another

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II 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

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

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

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created. + Inheritance + Inheritance Classes that we design in Java can be used to model some concept in our program. For example: Pokemon a = new Pokemon(); Pokemon b = new Pokemon() Sometimes we need to create

More information

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

Has-a Relationships. A pen has a or contains a ball Has-a Relationships A pen has a or contains a ball Has-a Relationships Has-a relationship Also called containment Cannot be implemented using inheritance Example: To implement the has-a relationship between

More information

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

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3: PROGRAMMING ASSIGNMENT 3: Read Savitch: Chapter 7 Programming: You will have 5 files all should be located in a dir. named PA3: ShapeP3.java PointP3.java CircleP3.java RectangleP3.java TriangleP3.java

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

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

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

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

Inheritance (cont.) Inheritance. Hierarchy of Classes. Inheritance (cont.) Inheritance Inheritance (cont.) Object oriented systems allow new classes to be defined in terms of a previously defined class. All variables and methods of the previously defined class, called superclass,

More information

Introduction to Design Patterns

Introduction to Design Patterns Introduction to Design Patterns First, what s a design pattern? a general reusable solution to a commonly occurring problem within a given context in software design It s not a finished design that can

More information

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

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

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

Object typing and subtypes

Object typing and subtypes CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3 Subtyping and Inheritance Interface The

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

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

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario The Story So Far... Classes as collections of fields and methods. Methods can access fields, and

More information

2. The object-oriented paradigm

2. The object-oriented paradigm 2. The object-oriented paradigm Plan for this section: Look at things we have to be able to do with a programming language Look at Java and how it is done there Note: I will make a lot of use of the fact

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Real world objects include things like your car, TV etc. These objects share two characteristics: they all have state and they all have behavior. Software objects are

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

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

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof Abstract Class Lecture 21 Based on Slides of Dr. Norazah Yusof 1 Abstract Class Abstract class is a class with one or more abstract methods. The abstract method Method signature without implementation

More information

Using Inheritance to Share Implementations

Using Inheritance to Share Implementations Using Inheritance to Share Implementations CS 5010 Program Design Paradigms "Bootcamp" Lesson 11.2 Mitchell Wand, 2012-2015 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

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

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

+ Questions about Assignment 5?

+ Questions about Assignment 5? + Inheritance + Questions about Assignment 5? + Review n Objects n data fields n constructors n Methods n Classes + Using the Ball class Treat in a manner very similar to a primitive data type. Ball[]

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Chapter - 2: Geometry and Line Generations

Chapter - 2: Geometry and Line Generations Chapter - 2: Geometry and Line Generations In Computer graphics, various application ranges in different areas like entertainment to scientific image processing. In defining this all application mathematics

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int

More information

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

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

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

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

QUESTIONS FOR AVERAGE BLOOMERS

QUESTIONS FOR AVERAGE BLOOMERS MANTHLY TEST JULY 2017 QUESTIONS FOR AVERAGE BLOOMERS 1. How many types of polymorphism? Ans- 1.Static Polymorphism (compile time polymorphism/ Method overloading) 2.Dynamic Polymorphism (run time polymorphism/

More information

Week 9. Abstract Classes

Week 9. Abstract Classes Week 9 Abstract Classes Interfaces Arrays (Assigning, Passing, Returning) Multi-dimensional Arrays Abstract Classes Suppose we have derived Square and Circle subclasses from the superclass Shape. We may

More information

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

8359 Object-oriented Programming with Java, Part 2. Stephen Pipes IBM Hursley Park Labs, United Kingdom 8359 Object-oriented Programming with Java, Part 2 Stephen Pipes IBM Hursley Park Labs, United Kingdom Dallas 2003 Intro to Java recap Classes are like user-defined types Objects are like variables of

More information

2. The object-oriented paradigm!

2. The object-oriented paradigm! 2. The object-oriented paradigm! Plan for this section:! n Look at things we have to be able to do with a programming language! n Look at Java and how it is done there" Note: I will make a lot of use of

More information

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

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

index.pdf January 21,

index.pdf January 21, index.pdf January 21, 2013 1 ITI 1121. Introduction to Computing II Circle Let s complete the implementation of the class Circle. Marcel Turcotte School of Electrical Engineering and Computer Science Version

More information

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

Use the scantron sheet to enter the answer to questions (pages 1-6) Use the scantron sheet to enter the answer to questions 1-100 (pages 1-6) Part I. Mark A for True, B for false. (1 point each) 1. Abstraction allow us to specify an object regardless of how the object

More information

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)

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) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

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

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

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

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 9 Robert Grimm, New York University 1 Review Last week Modules 2 Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab

More information

CSCE3193: Programming Paradigms

CSCE3193: Programming Paradigms CSCE3193: Programming Paradigms Nilanjan Banerjee University of Arkansas Fayetteville, AR nilanb@uark.edu http://www.csce.uark.edu/~nilanb/3193/s10/ Programming Paradigms 1 Java Packages Application programmer

More information

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

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

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

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1 Block I Unit 2 Basic Constructs in Java M301 Block I, unit 2 1 Developing a Simple Java Program Objectives: Create a simple object using a constructor. Create and display a window frame. Paint a message

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

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

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism Ibrahim Albluwi Composition A GuitarString has a RingBuffer. A MarkovModel has a Symbol Table. A Symbol Table has a Binary

More information

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1 Inheritance & Polymorphism Recap Inheritance & Polymorphism 1 Introduction! Besides composition, another form of reuse is inheritance.! With inheritance, an object can inherit behavior from another object,

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

5.6.1 The Special Variable this

5.6.1 The Special Variable this ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to And unfortunately, beyond the basic ideas there are a lot of

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

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

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with. 1 Outline TOPIC 3 INTRODUCTION TO PROGRAMMING Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Reviewing OO Concepts

Reviewing OO Concepts Reviewing OO Concepts Users want to draw circles onto the display canvas. public class Circle { // more code here SWEN-261 Introduc2on to So3ware Engineering Department of So3ware Engineering Rochester

More information

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

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation CSE 452: Programming Languages Data Abstraction and Object-Orientation Previous Lecture Abstraction Abstraction is the elimination of the irrelevant and the amplification of the essential Robert C Martin

More information

INHERITANCE - Part 1. CSC 330 OO Software Design 1

INHERITANCE - Part 1. CSC 330 OO Software Design 1 INHERITANCE - Part 1 Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors CSC 330 OO Software Design 1

More information

CST242 Object-Oriented Programming Page 1

CST242 Object-Oriented Programming Page 1 CST4 Object-Oriented Programming Page 4 5 6 67 67 7 8 89 89 9 0 0 0 Objected-Oriented Programming: Objected-Oriented CST4 Programming: CST4 ) Programmers should create systems that ) are easily extensible

More information

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

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance? INHERITANCE - Part 1 OOP Major Capabilities Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors encapsulation

More information

INHERITANCE - Part 1. CSC 330 OO Software Design 1

INHERITANCE - Part 1. CSC 330 OO Software Design 1 INHERITANCE - Part 1 Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors CSC 330 OO Software Design 1

More information