Person class. A class can be derived from an existing class by using the form

Size: px
Start display at page:

Download "Person class. A class can be derived from an existing class by using the form"

Transcription

1 Person class //Person.java - characteristics common to all people class Person { Person(String name) { this.name = name; void setage(int age) { this.age = age; void setgender(gender gender) { this.gender = gender; void setname(string name) { this.name = name; int getage() { return age; Gender getgender() { return gender; String getname() { return name; static enum Gender {M, F private String name; private int age; private Gender gender; A class can be derived from an existing class by using the form class class-name extends superclass-name { The new class is a subclass of the class from which it is derived, its superclass. The keyword extends defines this relationship. The subclass being defined automatically inherits all the data members and methods of its superclass. The keyword super is used to refer to the superclass object that is implicitly part of the subclass object.

2 Student class //Student.java - an example subclass class Student extends Person { Student(String name) { super(name); void setcollege(string college) { this.college = college; void setgpa(double gpa) { this.gpa = gpa; void setyear(yearinschool year) { this.year = year; String getcollege() { return college; double getgpa() { return gpa; YearInSchool getyear() { return year; static enum YearInSchool { frosh, sophmore, junior, senior private String college = "Unknown"; private YearInSchool year; // frosh, sophomore, private double gpa; //0.0 to 4.0 //StudentTest.java class StudentTest { public static void main(string[] args) { Student student = new Student("Jane Programmer"); student.setage(21); student.setgender(person.gender.f); student.setcollege("ucsc"); student.setyear(student.yearinschool.frosh); student.setgpa(3.75f); System.out.println(student.toString()); Example import java.awt.color; class Rectangle { private int x, y, height, width; public void draw() { public void move(int dx, int dy){ class ColoredRectangle extends Rectangle { private Color FillColor; public Color getfillcolor() { return this.fillcolor; public void setfillcolor(color c) { this.fillcolor = c; public void move(int dx, int dy){ Sub class can override the methods defined by the super class. Overridden methods should have same signature and same return type. Java implements Run Time Polymorphism by method overriding. Call to overridden methods is resolved at run time. Call to a overridden method is not decided by the type of reference variable. Rather it is decided by type of the object referred to.

3 class A { System.out.println("Hello This is show() in A"); B class overrides show() class B extends A { method from super class A System.out.println("Hello This is show() in B"); class override { public static void main(string args[]) { // super class reference variable // can point to sub class object A a1 = new A(); a1 = new B(); Call to show() of A class Call to show() of B class class A { void show(int a) { System.out.println("Hello This is show() in A"); class B extends A { System.out.println("Hello This is show() in B"); class override1 { public static void main(string args[]) { // A a1 = new B(); // A a1 = new A(); a1.show(10); B b1 = new B(); b1.show(10); b1.show(); Is this Method Overriding NO OUTPUT Hello This is show() in A Hello This is show() in A Hello This is show() in B Super class reference variable can refer to a sub class object. Super class variable if refers to sub class object can call only overridden methods. Call to an overridden method is decided by the type of object referred to. A a1 = new B(); // call to show() of B a1 = new C(); // call to show() of C a1 = new D(); // call to show() of D A B C D Assume show() Method is Overridden by sub classes class A { System.out.println("Hello This is show() in A"); class B extends A { System.out.println("Hello This is show() in B"); class C extends A { System.out.println("Hello This is show() in C"); class D extends A { System.out.println("Hello This is show() in D");

4 class override2 { public static void main(string args[]) { A a1 = new A(); a1 = new B(); a1 = new C(); a1 = new D(); Hello This is show() in A Hello This is show() in B Hello This is show() in C Hello This is show() in D class A {. class B extends A {. void show(int x) { void print() { A a1 = new B(); a1.show() ; // Valid a1.show(10); // Error!! a1.print(); // Error!! When a super class variable points to a sub class object, then it can only call overridden methods of the sub class. When you create an object of the derived class, it contains within it a subobject of the base class. It s essential that the base-class subobject be initialized correctly. perform the initialization in the constructor by calling the base-class constructor Java automatically inserts calls to the base-class constructor in the derived-class constructor. class Art { Art () { System.out.println("Art constructor"); class Drawing extends Art { Drawing () { System.out.println( Drawing constructor"); public class Cartoon extends Drawing { public Cartoon() { System.out.println("Cartoon constructor"); public static void main(string[] args) { Cartoon x = new Cartoon(); <Output> java Cartoon Art constructor Drawing constructor Cartoon construtor

5 If your class doesn t have default arguments, or if you want to call a base-class constructor that has an argument, you must explicitly write the calls to the base-class constructor using the super keyword and the appropriate argument list. class Game { Game (int i) { System.out.println( Game constructor"); class BoardGame extends Game { BoardGame (int i) { super (i); System.out.println( Game constructor"); public class Chess extends BoardGame { public Chess () { super (11); System.out.println( Chess constructor"); public static void main(string[] args) { Chess x = new Chess (); In Java, groups of related classes can be placed in a package. The first reason in for package access. A field or method that is defined without any of the access modifiers public, protected, or private can be accessed only from a method in a class from the same package. The second reason for using packages is to provide separate name spaces. Example: com.coolsoft.containers.stack, java.util.stack If you don t call the base-class constructor in BoardGame( ), the compiler will complain that it can t find a constructor of the form Game( ). 17 Whenever you want to use a class from an existing package, you need to use an import statement to import the class. Example: import java.util.*; import java.util.scanner; Every Java program can use classes from one unnamed package. Any classes in a single directory on your computer s disk that don t specify a package name are part of the same unnamed package. To place the classes in a named package, you need to do two things: (1) add a package statement to the top of each class in the package, and (2) place the classes in an appropriately named location on your computer s disk.

6 protected Example: Person and Student classes into a package called jbd.database //Person.java - characteristics common to all people package jbd.database; class Person { Person(String name) { this.name = name; //Student.java - an example subclass package jbd.database; class Student extends Person { Student(String name) { super(name); We need to place the source files in a subdirectory where the path to the subdirectory from the current directory is the same as the package name replacing any dots in the package name with the pathname separator for the local file system. Linux: jbd/databases/person.java, jbd/databases/student.java Compile: javac jbd/databases/*.java Access to a protected member from other classes is permitted only if the accessing class is a subclass of the class with the protected member. package jbd.database; public class Person { protected String name; protected int age; protected Gender gender; import jbd.database.*; class Driver extends Person { public boolean needsdrivered() { if (age < 25) return true; else return false; (1) Private Use this level whenever possible. You can make changes to private members by examining only the class containing the member. This restriction provides maximum information hiding. (2) Package Use this level when one class needs to be aware of some implementation details of another class in the same package. You may use package access for fields that are used heavily by other classes in the same package. (3) Protected Use this level when designing a class to be reused via inheritance from outside the package in which it is defined. You should carefully consider any decision to export a protected member. Such exporting seriously weakens information hiding and makes program maintenance significantly more difficult and error prone. (4) Public Reserve use of this level for the required interface elements to a class or package. You should never expose unnecessary implementation details with public access. Exporting a field with public access is very unusual, unless the field is also declared to be final. In Java, everything inherits from class Object. Object is generic, in that any operation applicable to an instance of the class Object is applicable to an instance of any class. Generic methods tostring () equals () Return true if elements have the same value. It returns true if and only if the two references refer to the same object. By overriding equals() we can write a generic methods that need to check if two objects are equal.

7 An abstract class is used to derive other (concrete) classes. An abstract class usually provides some complete method definitions, but leaves some undefined, requiring all subclasses to provide definitions for the undefined methods. abstract class class-name { abstract type method id(argument-list); //other concrete and abstract methods An abstract method is used to defer the implementation decision of the computation to a subclass. For example, we could create a collection of different types of counter classes, all with some common features. abstract public class AbstractCounter { protected int value; abstract public void click(); public int get() { return value; public void set(int x) { value = x; public class Counter extends AbstractCounter { public void click() { value = (value + 1) % 100; public class CounterByTwo extends AbstractCounter { public void click() { value = (value + 2) % 100; public class CounterTest { public static void main (String args[]) { // AbstractCounter absctr = new AbstractCounter (); // -> Error!! You cannot create an object of an abstract class. AbstractCounter absctr = new Counter (); absctr.click (); absctr.click (); System.out.println ( value = + absctr.get ()); absctr = new CounterByTwo (); absctr.click (); absctr.click (); System.out.println ( value = + absctr.get ()); Output : value = 2 value = 4 An interface in Java, is essentially an pure abstract class - all methods are abstract. An interface can contain only abstract methods, and constants. There are no instance variables. interface Instrument { // Compile-time constant: int I = 5; // static & final // Cannot have method definitions: void play(note n); String what(); void adjust(); An interface is allowed to have only public methods, and by convention the keyword public is omitted. Because all methods in an interface are abstract, the keyword abstract is also omitted.

8 Implementing an interface is like extending an abstract class. A new class implementing the interface uses the keyword implements. The class that implements the interface must provide an implementation for all methods in the interface. class Percussion implements Instrument { public void play (Note n) { System.out.println("Percussion.play() " + n ); public String what() { return "Percussion"; public void adjust() { class Wind implements Instrument { public void play (Note n) { System.out.println("Wind.play() " + n); public String what() { return "Wind"; public void adjust() { Just as with abstract classes, you can declare variables and parameters to be of an interface type, but you cannot create objects of an interface type. Using the declarations on the previous slides, new Instrument() would be illegal. You could declare a variable or parameter to be of type Instrument. This variable would always either be null or refer to an instance of some class that implements the interface Instrument. Because an interface has no implementation at all that is, there is no storage associated with an interface there s nothing to prevent many interfaces from being combined. This is valuable because there are times when you need to say An x is an a and a b and a c. In C++, this act of combining multiple class interfaces is called multiple inheritance. It carries some rather sticky baggage because each class can have an implementation. In Java, you can perform the same act, but only one of the classes can have an implementation. 31 In Java, If you inherit from a non-interface, you can inherit from only one. All the rest of the base elements must be interfaces. 32

9 interface CanFight { void fight(); interface CanSwim { void swim(); interface CanFly { void fly(); class ActionCharacter { public void fight() { class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { public void swim() { public void fly() { public class Adventure { public static void t (CanFight x) { x.fight(); public static void u (CanSwim x) { x.swim(); public static void v (CanFly x) { x.fly(); public static void w (ActionCharacter x) { x.fight (); public static void main(string[] args) { Hero h = new Hero(); t(h); // Treat it as a CanFight u(h); // Treat it as a CanSwim v(h); // Treat it as a CanFly w(h); // Treat it as an ActionCharacter 33 You can easily add new method declarations to an interface by using inheritance. You can also combine several interfaces into a new interface with inheritance. 34 interface Monster { void menace(); interface DangerousMonster extends Monster { void destroy(); interface Lethal { void kill(); interface Vampire extends DangerousMonster, Lethal { void drinkblood(); class DragonZilla implements DangerousMonster { public void menace() { public void destroy() { class VeryBadVampire implements Vampire { public void menace() { public void destroy() { public void kill() { public void drinkblood() { public class HorrorShow { static void u (Monster b) { b.menace(); static void v (DangerousMonster d) { d.menace(); d.destroy(); static void w (Lethal l) { l.kill(); public static void main(string[] args) { DangerousMonster barney = new DragonZilla(); u (barney); v (barney); Vampire vlad = new VeryBadVampire(); u (vlad); v (vlad); w (vlad); 35 36

10 public abstract class Shape { protected int x, y; public abstract double area(); public abstract double circumference(); public void move (int x1, int y1) { x += x1; y += y1; public class Circle exrtends Shape { public Circle () { r = 0; public double circumference () { return Math.PI * 2 * r; public double area () { return Math.PI * r * r; public int getradius () { return r; public void setradius (int r) { this.r = r; import java.awt.graphics; interface Drawable { void paint(graphics g); import java.awt.*; public class DrawableCircle extends Circle implements Drawable { public DrawableCircle() { this(0, 0, 0); public DrawableCircle (int x, int y, int r) { super(r); this.x = x; this.y = y; public void paint(graphics g) { g.drawoval (x-r, y-r, 2*r, 2*r); g.drawstring (String.valueOf(area()), x-r, y ); 37 if (x intanceof Shape) // x is a Shape, act accordingly else // x is not a Shape, act accordingly Person person = new Student(); if (person instanceof Student) { Student student = (Student)person; // operate on student Some illegal casts can be determined at compile time, others can only be detected at runtime. Trying to cast a Person into a String is a compile time error. The compiler knows that String is not a subclass of Person and hence the cast is always illegal. Trying to cast a Person into a Student, when the Person is not a Student, is a runtime error - even if YOU can see that this person couldn't possibly be a Student. The following can only be detected at runtime, even though you can see it is clearly illegal. Person person = new Person(); Student student = (Student)person;

Person class. A class can be derived from an existing class by using the form

Person class. A class can be derived from an existing class by using the form Person class //Person.java - characteristics common to all people class Person { Person(String name) { this.name = name; void setage(int age) { this.age = age; void setgender(gender gender) { this.gender

More information

8. Interfaces & Inner Classes

8. Interfaces & Inner Classes 8. Interfaces & Inner Classes 1 In Chapter 7 you learned about the abstract keyword, which allows you to create one or more methods in a class that have no definitions. The interface keyword produces a

More information

An example from Zoology

An example from Zoology Inheritance Ch. 10 An example from Zoology Mammal Bear Whale Brown Polar Humpback Gray 2 An example from java.lang Object Number String YourClass Long Integer Double Float 3 DefiniPons Inheritance classes

More information

Reusing Classes in Java. Java - Inheritance/Polymorphism/Interface. Inheritance. Simple Example of Composition. Composition.

Reusing Classes in Java. Java - Inheritance/Polymorphism/Interface. Inheritance. Simple Example of Composition. Composition. Reusing Classes in Java Composition A new class is composed of object instances of existing classes. Java - Inheritance/Polymorphism/Interface CS 4354 Summer II 2015 Jill Seaman Fields of one class contain

More information

Polymorphism. OOAD 1998/99 Claudia Niederée, Joachim W. Schmidt Software Systems Institute

Polymorphism. OOAD 1998/99 Claudia Niederée, Joachim W. Schmidt Software Systems Institute Polymorphism Polymorphism Abstract Classes Interfaces OOAD 1998/99 Claudia Niederée, Joachim W. Schmidt Software Systems Institute c.niederee@tu-harburg.de http://www.sts.tu-harburg.de Polymorphism A Circle

More information

Reusing Classes. Hendrik Speleers

Reusing Classes. Hendrik Speleers Hendrik Speleers Overview Composition Inheritance Polymorphism Method overloading vs. overriding Visibility of variables and methods Specification of a contract Abstract classes, interfaces Software development

More information

Inheritance. Inheritance

Inheritance. Inheritance 1 2 1 is a mechanism for enhancing existing classes. It allows to extend the description of an existing class by adding new attributes and new methods. For example: class ColoredRectangle extends Rectangle

More information

CMSC 132: Object-Oriented Programming II. Inheritance

CMSC 132: Object-Oriented Programming II. Inheritance CMSC 132: Object-Oriented Programming II Inheritance 1 Mustang vs Model T Ford Mustang Ford Model T 2 Interior: Mustang vs Model T 3 Frame: Mustang vs Model T Mustang Model T 4 Compaq: old and new Price:

More information

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I

Goals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I CSE1030 Introduction to Computer Science II Lecture #9 Inheritance I Goals for Today Today we start discussing Inheritance (continued next lecture too) This is an important fundamental feature of Object

More information

CIS 110: Introduction to computer programming

CIS 110: Introduction to computer programming CIS 110: Introduction to computer programming Lecture 25 Inheritance and polymorphism ( 9) 12/3/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Inheritance Polymorphism Interfaces 12/3/2011

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

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

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

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

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

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every

More information

Week 5-1: ADT Design

Week 5-1: ADT Design Week 5-1: ADT Design Part1. ADT Design Define as class. Every obejects are allocated in heap space. Encapsulation : Data representation + Operation Information Hiding : Object's representation part hides,

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

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 3, 2011 G. Lipari (Scuola Superiore Sant

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Polymorphism, Abstract Classes, Interfaces Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant

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

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC Topic 7: Inheritance Reading: JBD Sections 7.1-7.6 1 A Quick Review of Objects and Classes! An object is an abstraction that models some thing or process! Examples of objects:! Students, Teachers, Classes,

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

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

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

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

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

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

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

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

AP CS Unit 6: Inheritance Notes

AP CS Unit 6: Inheritance Notes AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything

More information

core Advanced Object-Oriented Programming in Java

core Advanced Object-Oriented Programming in Java core Web programming Advanced Object-Oriented Programming in Java 1 2001-2003 Marty Hall, Larry Brown http:// Agenda Overloading Designing real classes Inheritance Advanced topics Abstract classes Interfaces

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

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Advanced Object-Oriented. Oriented Programming in Java. Agenda. Overloading (Continued)

Advanced Object-Oriented. Oriented Programming in Java. Agenda. Overloading (Continued) Advanced Object-Oriented Oriented Programming in Java Agenda Overloading Designing real classes Inheritance Advanced topics Abstract classes Interfaces Understanding polymorphism Setting a CLASSPATH and

More information

Informatik II (D-ITET) Tutorial 6

Informatik II (D-ITET) Tutorial 6 Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,

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

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

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

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Abstract class & Interface

Abstract class & Interface Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) Lab 3 Abstract class & Interface Eng. Mohammed Abdualal Abstract class 1. An abstract

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

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

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5, Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &

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

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

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

Extending Classes (contd.) (Chapter 15) Questions:

Extending Classes (contd.) (Chapter 15) Questions: Extending Classes (contd.) (Chapter 15) Questions: 1 1. The following C++ program compiles without any problems. When run, it even prints out the hello called for in line (B) of main. But subsequently

More information

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

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

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

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

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

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes COMP200 - Object Oriented Programming: Test One Duration - 60 minutes Study the following class and answer the questions that follow: package shapes3d; public class Circular3DShape { private double radius;

More information

Programming in the Large II: Objects and Classes (Part 2)

Programming in the Large II: Objects and Classes (Part 2) Programming in the Large II: Objects and Classes (Part 2) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

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

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Create a Java project named week10

Create a Java project named week10 Objectives of today s lab: Through this lab, students will examine how casting works in Java and learn about Abstract Class and in Java with examples. Create a Java project named week10 Create a package

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Debapriyo Majumdar Programming and Data Structure Lab M Tech CS I Semester I Indian Statistical Institute Kolkata August 7 and 14, 2014 Objects Real world objects, or even people!

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

Basic Object-Oriented Concepts. 5-Oct-17

Basic Object-Oriented Concepts. 5-Oct-17 Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains

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

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

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass

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

Object Oriented Modeling

Object Oriented Modeling Object Oriented Modeling Object oriented modeling is a method that models the characteristics of real or abstract objects from application domain using classes and objects. Objects Software objects are

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

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

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

Abstract, Interface, GUIs. Ch. 11 & 16

Abstract, Interface, GUIs. Ch. 11 & 16 Abstract, Interface, GUIs Ch. 11 & 16 Abstract A class declared abstract cannot be instan:ated (we can t create an object of its type). A method declared abstract MUST be implemented if a class subclasses

More information

C08: Inheritance and Polymorphism

C08: Inheritance and Polymorphism CISC 3120 C08: Inheritance and Polymorphism Hui Chen Department of Computer & Information Science CUNY Brooklyn College 2/26/2018 CUNY Brooklyn College 1 Outline Recap and issues Project progress? Practice

More information

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Week 9 Lab - Use of Classes and Inheritance 8th March 2018 SP1-Lab9-2018.ppt Tobi Brodie (Tobi@dcs.bbk.ac.uk) 1 Lab 9: Objectives Exercise 1 Student & StudentTest classes 1.

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

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

OOP: Key Concepts 09/28/2001 1

OOP: Key Concepts 09/28/2001 1 OOP: Key Concepts Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring 09/28/2001 1 Overview of Part

More information

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: has a CSE143 Sp Student. CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches

More information

Methods Common to all Classes

Methods Common to all Classes Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;

More information

Lecture 5: Inheritance

Lecture 5: Inheritance McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability

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

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented

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

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

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

CSE 143 Lecture 20. Circle

CSE 143 Lecture 20. Circle CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public

More information

Introduction to Computation and Problem Solving

Introduction to Computation and Problem Solving Class 13: Inheritance and Interfaces Introduction to Computation and Problem Solving Prof. Steven R. Lerman and Dr. V. Judson Harward 2 More on Abstract Classes Classes can be very general at the top of

More information

Inheritance and Polymorphism. CS180 Fall 2007

Inheritance and Polymorphism. CS180 Fall 2007 Inheritance and Polymorphism CS180 Fall 2007 Definitions Inheritance object oriented way to form new classes from pre-existing ones Superclass The parent class If class is final, cannot inherit from this

More information

Java Classes, Inheritance, and Interfaces

Java Classes, Inheritance, and Interfaces Java Classes, Inheritance, and Interfaces Introduction Classes are a foundational element in Java. Everything in Java is contained in a class. Classes are used to create Objects which contain the functionality

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

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

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

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

Design Patterns. Design Patterns 1. Outline. Design Patterns. Bicycles Simulator 10/26/2011. Commonly recurring patterns of OO design

Design Patterns. Design Patterns 1. Outline. Design Patterns. Bicycles Simulator 10/26/2011. Commonly recurring patterns of OO design G52APR Applications Programming Design Patterns 1 Design Patterns What is design patterns? The design patterns are languageindependent strategies for solving common object-oriented design problems. Jiawei

More information

Polymorphism and Inheritance

Polymorphism and Inheritance Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and

More information

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at  Interfaces. Today Book-keeping Inheritance Subscribe to sipb-iap-java-students Interfaces Slides and code at http://sipb.mit.edu/iap/java/ The Object class Problem set 1 released 1 2 So far... Inheritance Basic objects,

More information