Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.

Slides:



Advertisements
Similar presentations
Chapter 1 Inheritance University Of Ha’il.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Class Hierarchy (Inheritance)
CS 211 Inheritance AAA.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
CSCI 143 OOP – Inheritance 1. What is Inheritance? A form of software reuse Create a new class from an existing class – Absorb existing class data and.
1 Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding l Object:
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
© 2004 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 : Inheritance Intermediate Java Programming Summer 2007.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Intro to OOP with Java, C. Thomas Wu
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
What is inheritance? It is the ability to create a new class from an existing class.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
JAVA WORKSHOP SESSION – 3 PRESENTED BY JAYA RAO MTech(CSE) NEWTON’S INSTITUTE OF ENGINEERING 1.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Chapter 8 Specialization aka Inheritance. 2 Inheritance  Review of class relationships  Uses – One class uses the services of another class, either.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
1 Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called the parent class, or.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Topics Inheritance introduction
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Classes, Interfaces and Packages
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
UNIT-2. Inheritance –Definition Single Inheritance Benefits of inheritance Member access rules super classes Polymorphism Method overriding Using final.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
Inheritance and Polymorphism
03/10/14 Inheritance-2.
UNIT-2.
Week 8 Lecture -3 Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Modern Programming Tools And Techniques-I Inheritance
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Inheritance, Polymorphism, and Interfaces. Oh My
INHERITANCE.
Overriding Methods & Class Hierarchies
Java Inheritance.
Chapter 8 Inheritance Part 2.
Chapter 11 Inheritance and Polymorphism Part 1
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Inheritance in Java

Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible only to methods of the class in which they are declared –Declaring instance variables private is known as data hiding public keywordpublic keyword –Exposes variables or methods outside the Class. –Declaring public methods is know as defining the class’ public interface. Protected keywordProtected keyword –Provides limited access –Provides access to sub classes but not to the classes outside a package

Summary Situation public protected default private Accessible to class from same package? yes no Accessible to class from different package? yes no, unless it is a subclass no

Inheritance Inheritance allows a software developer to reuse classes by deriving a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class

Inheritance Relationship Animal weight : int + getWeight() : int Bird Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent

Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal { // class contents public void fly() {…}; }

Class Hierarchy Good class design puts all common features as high in the hierarchy as reasonable inheritance is transitive –An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object

Class inheritance The inclusion of members of a base class in a derived class so that they are accessible in that derived class is called class inheritance. An inherited member of a base class is one that is accessible within the derived class. If a base class member is not accessible in a derived class, then it is not an inherited member of the derived class.

Class inheritance An inherited member of a derived class is a full member of that class and is freely accessible to any method in the class. The non- inherited members are also part of the base class object.

Inheriting Data Members

Hidden Data Members Variables of same name both in base class and derived class Use of keyword super

Inherited Methods Methods other than constructors are inherited in the same way as data members. The constructors are not inherited.

Example // A simple example of inheritance. // Create a superclass. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); }

class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println();

/* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); }

OUTPUT The output from this program is shown here: Contents of superOb: i and j: Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24

Example public class Animal { public Animal(String aType) { type = new String(aType); } public String toString() { return “This is a “ + type; } private String type; }

public class Dog extends Animal { // constructors for a Dog object private String name; private String breed; }

Constructors of the Derived Class public class Dog extends Animal { public Dog(String aName) { super(“Dog”); name = aName; breed = “Unknown”; } public Dog(String aName, String aBreed) { super(“Dog”); name = aName; breed = aBreed; } private String name; private String breed; }

Overriding a Base Class Method public String toString() { return “It’s “ + name + “ the “ + breed; }

Method Overriding A child class can override the definition of an inherited method in favor of its own –that is, a child can redefine a method that it inherits from its parent –the new method must have the same signature as the parent's method, but can have different code in the body In java, all methods except of constructors override the methods of their ancestor class by replacement. E.g.: –the Animal class has method eat() –the Bird class has method eat() and Bird extends Animal –variable b is of class Bird, i.e. Bird b = … –b.eat() simply invokes the eat() method of the Bird class If a method is declared with the final modifier, it cannot be overridden

Another use of Super public String toString() { return super.toString() + “\nIt’s “ + name + “ the “ + breed; }

23 Overloading vs. Overriding Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overriding lets you define a similar operation in different ways for different object types

Guidelines to Choose Access Attributes Methods likely to be used as external interface to a class should be declared as public. Do not make data members public unless they are constants intended for general use. If you expect other people will use your classes as base classes, your classes will be more secure if you keep data members private, and provide public methods for accessing and manipulating them when necessary.

Use protected when you want a limited access to the subclasses in other packages

26 The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class –even if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class –the Object class is therefore the ultimate root of all class hierarchies The Object class contains a few useful methods, which are inherited by all classes –toString() –equals() –clone()

The Object Class: the toString Method That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance The toString method in the Object class is defined to return a string that contains the name of the object’s class and a hash value Every time we have defined toString, we have actually been overriding it

The Object Class: the equals Method The equals method of the Object class determines if two variables point to the same object (more shortly) Many classes (which all implicitly extend an Object class) override equals to define equality in some other way, e.g. Integer.equals looks at the represented integer, etc.

EXAMPLE class Animal { private String type; public Animal(String aType) { type = new String(aType); } public void eat() { System.out.println("Animal eat"); }

EXAMPLE class Dog extends Animal { private String name; private String breed; public Dog(String aName) { super("Dog"); name = aName; breed = "Unknown"; } public Dog(String aName, String aBreed) { super("Dog"); name = aName; breed = aBreed; } public void eat(){ System.out.println("Dog eat"); }}

EXAMPLE class Test { public static void main(String args[]) { Animal a = new Animal(“Unknown"); Animal b=a; Dog d = new Dog("dog"); System.out.println(a.toString()); System.out.println(b.toString()); System.out.println(d.toString()); System.out.println(a.equals(b)); System.out.println(a.equals(d)); }

LAB PRACTICE Create a parent class “person” Add instance variable like name. Add methods like setname(), getname() Create a child class “student” which inherits from person class Add instance variable like stunum. Add methods like setstunum(), getstunum() Create another class Test which contains main() method. Create object of child class n call methods Setname() Setstunum() Getname() Getstunum()

LAB PRACTICE Create a parent class “Bicycle” Add instance variables like speed,gear, initialize via constructor Add methods like speedUp(), changeGear(), applyBrakes(), printStates(); Create a child class “MountainBike” which inherits from Bicycle class Add instance variable like seatheight, initialize via constructor. Add methods like setHeight(), getHeight()

LAB PRACTICE Create another class Test which contains main() method. Create object of child class n call methods printStates() speedUp() changeGear() applyBrakes() printStates() setHeight() getHeight()

Lab Practice Now override printStates() method in child class Create objects of parent class & child class in main() Call methods for parent class in the following sequence printStates() speedUp() changeGear() applyBrakes() printStates() Call methods for child class in the following sequence printStates() speedUp() changeGear() applyBrakes() setHeight() printStates()