Programming - 2. Inheritance. A process by which a class can extend another class, inheriting all its

Similar documents
Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Java Interview Questions and Answers

Java Programming Language

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 13 - Inheritance

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Inheritance, overloading and overriding

Building Java Programs

CS193j, Stanford Handout #10 OOP 3

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

J a v a Quiz (Unit 3, Test 0 Practice)

History OOP languages Year Language 1967 Simula Smalltalk

AP Computer Science Java Subset

D06 PROGRAMMING with JAVA

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

CS 111 Classes I 1. Software Organization View to this point:

CS170 Lab 11 Abstract Data Types & Objects

Compile-time type versus run-time type. Consider the parameter to this function:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

Fundamentals of Java Programming

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Advanced Data Structures

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

PHP Object Oriented Classes and objects

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Object-Oriented Programming in Java

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

CS506 Web Design and Development Solved Online Quiz No. 01

Introducing Variance into the Java Programming Language DRAFT

Android Application Development Course Program

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

13 Classes & Objects with Constructors/Destructors

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Lecture 1 Introduction to Android

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Object-Oriented Programming: Polymorphism

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Manual For Using the NetBeans IDE

iphone SDK Enrolled students will be invited to developer program Login to Program Portal Request a Certificate Download and install the SDK

Lab Manual: Using Rational Rose

Description of Class Mutation Mutation Operators for Java

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

STATIC VARIABLE/ METHODS, INHERITANCE, INTERFACE AND COMMAND LINE ARGUMENTS

Java EE Web Development Course Program

UML Class Diagrams (1.8.7) 9/2/2009

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

A Practical Guide to Test Case Types in Java

java Features Version April 19, 2013 by Thorsten Kracht

Glossary of Object Oriented Terms

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Documentum Developer Program

The Interface Concept

Using Inheritance and Polymorphism

Agile Software Development

Install Java Development Kit (JDK) 1.8

Lecture 7: Class design for security

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Chapter 5 Names, Bindings, Type Checking, and Scopes

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

A Scala Tutorial for Java programmers

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Programmation 2. Introduction à la programmation Java

Java (12 Weeks) Introduction to Java Programming Language

Android Studio Application Development

An Introduction To UML Class Diagrams Classes

Web Service Caching Using Command Cache

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

The C Programming Language course syllabus associate level

Abstract Classes. Suppose we want write a program that manipulates various types of bank accounts. An Account typically has following features;

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Construction of classes with classes

Kotlin for Android Developers

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Java Application Developer Certificate Program Competencies

ICOM 4015: Advanced Programming

Concepts and terminology in the Simula Programming Language

Contents. 9-1 Copyright (c) N. Afshartous

3 Improving the Crab more sophisticated programming

Kotlin for Android Developers (Preview)

Transcription:

Inheritance What is Inheritance? A process by which a class can extend another class, inheriting all its variables, methods, while redefining (overriding) some of them, and/or adding its own. Thus inheritance promotes code re-use. If a class B needs to define some behavior and a lot of that behavior is pre-defined in any other class A then instead of defining the entire behavior again, the class B should inherit from that class A. An Example Inheritance allows classes to be defined in terms of other classes. For example, mountain bikes, road bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, road bikes, and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, road bikes, and tandems. This relationship is shown in the following figure. Umair 2006, All Rights Reserved - 1 -

Tree Hierarchy Inheritance leads to hierarchy of classes. The classes arranged in tree hierarchy increases the understanding. For example consider the following tree hierarchy Person Employee Teacher Manager Inheritance Vocabulary (Buzzwords) Superclass Subclass - A superclass is the class above in the hierarchy. For example Person is a direct superclass of Employee and indirect superclass of Teacher or manager. - Sometimes also referred as parent or base class. - A superclass has fewer properties (as compared to subclass). - A supeclass is more general For example; Employee class is a general class as compare to Teacher as it (Employee) can represent teacher, manager, secretary, and clerical staff and so on. - A subclass is the class below (of super class) in the hierarchy. For example, Employee is a direct subclass of Person; also teacher is indirect subclass of Person but direct subclass of Employee. - Sometimes also refer as child or derived class. - A subclass generally has more properties (as compared to superclass) because by the rule of inheritance, a subclass inherits properties of superclass as well as defining/adding its (subclass) own. Tandem bicycles have two seats and Umair 2006, All Rights Reserved - 2 -

Sibling two sets of handle bars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. - A supeclass is more specific For example; Teacher class is a specific class as compare to Employee as it can only represent Teacher s category (Professors, Lecturers and Instructors etc) as compared to employee (general) class which can represent Teacher as well as Managers - Two children (subclasses) of the same parent class are called siblings. In the above example, Teacher and Manager are siblings. Is a/an relationship Subclass is a Superclass or an instance of a subclass is an instance of superclass since a subclass has all the properties of a superclass and some additional properties as well. Considering the above class hierarchy, we can say that Teacher is an Employee and rightly so as teacher is an employee from the university perspective. Also Manger is an Employee & Employee is a Person. Since Employee is parent of Teacher and Person is a parent of Employee, so by following the inheritance rule, Teacher is an Employee is a Person. So, Person is indirect parent of Teacher. By summing up the above discussion, we can conclude that Teacher is a Person. Umair 2006, All Rights Reserved - 3 -

Inheritance Warning Inheritance is the core part of OOP. Inheritance is a clever and appealing concept. However using it properly needs clarity of concept. A common error made by beginner OOP programmers is that they do not make use of inheritance. Let s make our concepts clear from the following example Horse/Zebra Example With inheritance, we define classes in terms of other classes. This can be a great shortcut if the classes are similar. Suppose you have the hierarchy of all the animal classes, except the zebra class. Now, you want to make a zebra class. What to do? - Option 1 - define the zebra class from scratch (Wrong) - Option 2 - Locate the horse class. Make Zebra class a subclass of Horse class Benefits Zebra inherits 90% of its behavior so NO coding requirement + time save. In the Zebra class, define the few things that are features of Zebras but not horses. What would you do if horses have some features that Zebras don t have - You ll see if the parent class of horses can do the job. Then you will inherit from the parent class of horse and not horse itself. Points to Remember Java doesn t support multiple inheritances, it only support single inheritance. It means that a class can only extend from one class at one time. All java classes inherit from Object class (more on it later). Things declared public in superclass are available/accessible to subclass and all other classes as well. Things declared protected in superclass are available/accessible to subclass and not to other classes. Things declared private are not directly accessible to subclass or any other class. Umair 2006, All Rights Reserved - 4 -

Whenever you construct the object of subclass, subclass constructor would be called as well as superclass constructor would also be called. - If you don t specify which superclass constructor to be called, the java will automatically call the default constructor of the superclass. (Example of these are coming up shortly). Comparison with C++ See handout on Similarities and Differences between C++ & Java. Constructors are Not Inherited Although a subclass inherits methods and variables from the parent class, it does not inherit constructors. If you don t write any constructor (no argument or parameterize) of subclass than java will write default constructor for you. Method Overriding The process of redefining a method, that is already defined in the superclass with same signature (name + parameters) and return type, in the subclass is called method overriding. Overriding allows the subclasses to modify behavior (method) as needed. Suppose that area method is defined in the Shape class and Circle class is a subclass of Shape class. So, area method through inheritance is available to Circle class but it is useless for Circle class since the area calculating methodology of circle ( r2 ח) is different of Shape. As a result, Circle class has to redefine area method (overriding) to achieve the desired behavior. Umair 2006, All Rights Reserved - 5 -

Inheritance using Java Keyword extends Keyword extends is used for defining inheritance between super and sub class as the subclass is extending the behavior and functionality of superclass. class Teacher extends Employee { Keyword super The keyword super is used for two purposes: To call the superclass constructor from the subclass constructor To call the superclasss method from subclass that is overridden in the subclass Both usage of the super keyword is shown in the coming up code example. Code Example Employee.java The Employee class has name and id as instance variables. Two constructors, default & parameterized are also provided. Other methods include setter/getters, display (capable of printing employee object on console) and tostring method (capable of converting employee object into string) is overridden here. Note: The tostring() method is actually defined in the Object class, and every class in java inherits from Object class whether extends kewords is specified or not class Employee{ protected int id; protected String name; //parameterized constructor public Employee(int id, String name){ this.id = id; this.name = name; Umair 2006, All Rights Reserved - 6 -

//default constructor public Employee(){ this (10, not set ); //setters public void setid (int id) { this.id = id; public void setname (String name) { this.name = name; //getters public int getid () { return id; public String getname () { return name; // displaying employee object on console public void display(){ System.out.println( in employee display method ); System.out.println("Employee id:" + id + " name:" + name); //overriding object s class tostring method public String tostring() { System.out.println( in employee tostring method ); return "id:" + id + "name:" + name; //end class Consider the following line of code in the default constructor of the Employee s class. this (10, not set ); As you already know, this is the keyword and here it is used to call the Employee class parameterize constructor. Hence, Keyword this can be used to call the other constructor of the same class. For example, to call the default constructor, write following code: this ( ); Umair 2006, All Rights Reserved - 7 -

Teacher.java The Teacher class extends from Employee class. The teacher class has an additional attribute i.e. qualification. Two constructors, default & parameterized are also defined. getter/setter is also defined for qualification. Display & tostring methods are overridden in this class. class Teacher extends Employee{ private String qual; //default constructor public Teacher () { //implicit call to superclass default construct qual = ""; //parameterized constructor public Teacher(int i, String n, String q){ super(i,n); //call to superclass const must be first line qual = q; //setter public void setqual (String qual){ this.qual = qual; //getter public String getqual(){ return qual; //overriding dispaly method of Employee class public void display(){ System.out.println("in teacher's display method"); super.display(); //call to superclass display method System.out.println("Teacher qualification:" + qual); //overriding tostring method of Employee class public String tostring() { System.out.println("in teacher's tostring method"); String emp = super.tostring(); return emp +" qualification:" + qual; //end class Umair 2006, All Rights Reserved - 8 -

The first usage of keyword super is to call superclass s constructors. This has been shown in the parameterize constructor of Teacher class to make call to parameterize constructor of the parent class i.e. Employee class. Note that we didn t use the super keyword in the default constructor of Teacher class but java will implicitly call the default (no argument) constructor of the Employee class. The second usage of super is to call the overridden methods. This has been shown in the display and tostring method of the Teacher class. Points to Remember The call to superclass constructor via keyword super must be the first line (as used in the parameterized constructor) or otherwise compiler will raise an error. Java will make call to superclass default constructor automatically if no one is specified in subclass constructor. If the method is not overridden in the subclass than there is no need to use the keyword super before method name. Test.java This class acts as a driver class as it contains the main method. Objects of Employee & Teacher class are created inside main and calls are made to display and tostring method using these objects. class Test{ public static void main (String args[]){ System.out.println("making object of employee"); Employee e = new Employee(89, "khurram ahmad"); System.out.println("making object of teacher"); Teacher t = new Teacher (91, "ali raza", "phd"); e.display(); //call to Employee class display method t.display(); //call to Teacher class display method System.out.println("Employee: " +e.tostring()); System.out.println("Teacher: " + t); //end of main //end class Umair 2006, All Rights Reserved - 9 -

Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes, by default, are derived from the Object class i.e. if a class is not explicitly defined to be the child of any superclass class, java makes it the child of the Object class Object class contains some useful methods like tostring(), equals() (for comparing references) etc. - As we didn t specify the superclass of the Employee class. So, java made Object class its superclass. That s why we have overridden tostring method in the Employee class. The Object class is therefore the ultimate root of all class hierarchies. The one hierarchy we discussed is modified as one given below assuming that Employee class inherits from Person class. Hence, the Object class will became the superclass of the Person class (ultimate root class). Object Person Employe Teacher Manager Umair 2006, All Rights Reserved - 10 -

References: Java tutorial: http://java.sun.com/docs/books/tutorial/java/javaoo/ Stanford university Umair 2006, All Rights Reserved - 11 -