Inheritance Chapter 5.

Slides:



Advertisements
Similar presentations
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Advertisements

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
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. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
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.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
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.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
1 More About Derived Classes and Inheritance Chapter 9.
Modern Programming Tools And Techniques-I
Creating Your Own Classes
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Inheritance and Polymorphism
Advanced Programming in Java
An Introduction to Inheritance
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Understanding Inheritance
Chapter 9 Inheritance and Polymorphism
Inheritance 2nd Lecture
Comp 249 Programming Methodology
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 9 Object-Oriented Programming: Inheritance
Extending Classes.
Lecture 22 Inheritance Richard Gesick.
Advanced Java Topics Chapter 9
Inheritance 2nd Lecture
Advanced Programming Behnam Hatami Fall 2017.
Java – Inheritance.
Inheritance 2nd Lecture
Java Programming, Second Edition
Fundaments of Game Design
Inheritance.
Chapter 11 Inheritance and Polymorphism
Chapter 8 Inheritance Part 2.
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
CMSC 202 Inheritance II.
Presentation transcript:

Inheritance Chapter 5

Chapter 5 5.0 Inheritance Inheritance concept Access levels Inheriting instances fields and methods Object class and method overriding Array of sub classes Three-level inheritance

Inheritance: Terminology There are a number of terms that you need to know in understanding inheritance. Field : a variable that is part of a class Method : a function that is part of a class Constructor : a special method that is called when an object is created Superclass : the class that is inherited from (parent class) Subclass : the class that does the inheriting (child class) extends : in Java the keyword extends means that a class will inherit from another class Overload : a method is overloaded if there are two or more methods with the same name in a class. Each overloaded method has a different set of parameters. That's how you can tell which one will get called. Override : a method is overridden if there is a method in the subclass that has the same name and the same set of parameters. The superclass method is then NOT inherited.

Inheritance: Concept Object-oriented programming allows classes to inherit commonly used state and behaviour from other classes. The idea of inheritance is simple but powerful. When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. Inheritance is a mechanism for a subclass to reuse code from a superclass. You can reuse fields and methods of the existing class without having to write them yourself. A mechanism that enables one class to inherit, both the behaviour and the attributes of another class. Inheritance allows a software developer to derive a new class from an existing one.

Inheritance: Concept 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. A subclass inherits all the members (fields, methods and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses but the constructors of the superclass can be invoked from the subclass.

Inheritance: Concept class mySuperClass Superclass typically is-a general purpose class. Subclass is a special case or customized version of the superclass. When subclass is created, it inherits data and methods from its superclass. Format for class inheritance is: class mySuperClass { //data and methods for the superclass} Subclass is usually located in its own java file. class mySubClass extends mySuperClass { ….. }

Inheritance: Concept Employee ContractEmployee Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class. Inheritance should create an is-a relationship, meaning the child is more specific version of the parent Employee ContractEmployee

Inheritance: Benefit of Inheritance Question: What are the benefits of inheritance? State and functionality can be "shared" among objects: Inheritance reduces program development time by allowing us to reuse code. When we extend a class someone else has already built, we only need to add our changes. This is especially useful in the context of modifying code. Since all the shared code is inherited, any changes in the top level classwill be automatically propagated to all subclasses. Substitutability/Polymorphism: A subclass can be used wherever an object of the superclassis required. An object of a single class can have multiple forms: either its own or that of one of the classes it extends. Specialization through extension: We may easily extended a class to behave like a specialized version of the superclass.

Inheritance: Benefit of Inheritance Question: What are the benefits of inheritance? code reuse reduce software complexity reduces program development time

Inheritance: Drawback of Inheritance Question: What are the drawbacks of inheritance? Forces inheritance of specification, and does not check for true subtype relationship. Subclasses are highly dependent on implementation of the superclass. Thus, "design and document for inheritance, or else prohibit it". Inheritance forces a set of methods and fields on a class. You may not want some of these, and it is not necessary that all of these are required. There is no concept of partial inheritance.

Inheritance: Access Level: Variables and Methods public Accessible anywhere class name is accessible protected Accessible in the package that contains the class Accessible in all subclasses private Accessible in the class only If no access level is given: Accessible in the package that contains the class. Accessible in subclasses defined in the package that contains the class. Not accessible in subclasses defined outside the package that contains the class.

Inheritance: Access Level: Variables and Methods Method Visibility Modifier Can be Accessed By public any class protected owning class, any subclass, any class in the same package Private owning class No Modifier owning class, any class in the same package

Inheritance: Implementation A class diagram is a visual tool that provides you with an overview of a class. It consists of a rectangle divided into three sections, the top section contains name of the class, middle section contains name and data types of the attributes and the bottom section contains the methods. Employee empNum: int empSal: double getEmpNum() : int getEmpSal() : double setEmpNum(int num) : int setEmpSal(double sal) : double The Employee class diagram

Inheritance: Implementation Superclass: class Employee Inheritance: Implementation public class Employee{ //class private int empNum; //attributes private double empSal; public Employee(){ //constructor empNum=0; empSal=0.0; } public Employee(int n, double s){ //constructor empNum=n; empSal=s; public int setEmpNum(int num){ //mutator return empNum= num; public double setEmpSal(double sal){ //mutator return empSal= sal; public int getEmpNum(){ //acessor return empNum; public double getEmpSal(){ //acessor return empSal;

Inheritance: Implementation You can create another class called EmployeeTerritory and provide three fields (empNum, empSal, empTerritory). Where empNum, empSal will be inherited from Employee Employee empNum: int empSal: double Employee() Employee():int, double getEmpNum(): int getEmpSal(): double setEmpNum(int num): int setEmpSal(double sal): double EmployeeTerritory empTerritory: int EmployeeTerritory() EmployeeTerritory():int,double,int getEmpTerritory(): int setEmpTerritory(int territory): int The figure shows the relation between Employee and the EmployeeTerritory is inheritance relationship.

Inheritance: Implementation When using inheritance to create EmployeeTerritory, programmer Save time because Employee fields and methods already exist Reduce errors because the Employee methods have already been used and tested Reduce the amount of learning required to use the new class A class may be the parent for a child class and may be a child of another class. Just as with human relationships, a person is a child of some humans and a parent to others. The syntax for deriving a child class from a parent class is: class childClass extends parentClass { // new characteristics of the child class go here}

Inheritance: Implementation: extends In Java, we use the reserved word extends to establish an inheritance relationship. To instantiates the object, such as: EmployeeTerritory AseanRep= new EmployeeTerritory(); AseanRep.getEmpNum(); AseanRep.getEmpSal(); AseanRep.getEmpTerritory();

Subclass: class establish an inheritance with Employee class EmployeeTerritory extends Employee{ private int empTerritory; public EmployeeTerritory(){ super(); empTerritory=0; } public EmployeeTerritory(int n, double s, int num){ super(n,s); public int getEmpTerritory(){ return empTerritory; public int setEmpTerritory(int num){ return empTerritory=num; establish an inheritance with Employee One instance variable Others inherited from Employee

Inheritance: Implementation: Proposition Inheritance is one-way proposition; a child inherits from a parent, not the other way around. For example Employee aClerk= new Employee(); Employee is the parent class and aClerk is an object of the parent class. Superclass does not have access to the subclass methods. e.g: aClerk.getEmpTerritory(); is NOT VALID The Employee object does not have the access to EmployeeTerritory methods. When creating the parent class, programmer does not know how many future subclasses it might have, or what their data or methods might look like.

Inheritance: Implementation: Constructor When writing a program, programmer tends to forget about initialize a library component. Thus, the resources used by the element are still retained and easily end up running out of resources (memory). This is the reason why constructor is needed. With constructor, a special method automatically called when an object is created. That will release the memory resources when it’s no longer being used (in additional to garbage collector). When we start a program we always initialize a field, e.g. for(x=0; y.length() < x; x++) Constructor works the same but instead of field it initialize the object. With constructor, the class designer can guarantee initialization of every object.

Inheritance: Implementation: Constructor What is a Constructor? A special type of method that is called when an object is created. In Java, constructors have the same name as their class and have no return value in their declaration. Purpose to create an instance of a class. Some of the differences between constructors and other Java methods: Constructors never have an explicit return type. Constructors cannot be directly invoked (the keyword new must be used). Constructors cannot be overridden, nor they are inherited. Constructors cannot be final. Constructors cannot be abstract. Constructors cannot be static.

Inheritance: The super Reference Accessing Superclass methods All classes have at least one constructor. A constructor is used to initialize a new object of that type and looks like a method with the same name as the class but without a return type. The Java constructor name is the same as the class name and is allowed multiple signatures. When creating a class that doesn’t have constructor, Java will automatically supply a default constructor –one that never requires arguments. When a superclass has a default constructor, you can create a subclass with or without its own constructor. However, if superclass contains only one constructor that require arguments, you must include at least one constructor for each for each subclass you create.

Inheritance: The super Reference Accessing Superclass methods Unlike members of a superclass, constructors of a superclass are not inherited by its subclasses, even though they have public visibility. You must define a constructor for a class or use the default constructor added by the compiler. The following statement calls the superclass’s constructor; super(); A constructor for a child class always starts with an invocation of one of the constuctors in the parent class. If the parent class has several constructors then the one which is invoked is determined by matching argument lists.

Inheritance: Constructor & super Reference Employee idNum: int balanceOwned: double Customer(int id, double bal)://constructor display(): void RegularCustomer discountRate: double RegularCustomer(int id, double bal, double disR): //constructor display(): void

Superclass Subclass constructor constructor call superclass constructor

Application class instantiates the object ?

Inheritance: The this Keyword You can use the keyword this as the opposite of super. It refers to another constructor in the same class. If used, it must be the first line of the constructor. It refer to the current object.

Inheritance: The this Keyword class Parent { String name = "Parent"; } class Child extends Parent { String name = "Child"; public void print() { System.out.println( name ); System.out.println( this.name); System.out.println( super.name); System.out.println( Parent.name); System.out.println( ((Parent)this).name); class SuperThis{ public static void main( String args[] ) { Child whoAmI= new Child(); whoAmI.print(); ?

Inheritance: Method Override (replace) A method is overridden if there is a method in the subclass that has the same name and the same set of parameters. The superclass method is then NOT inherited. Overriding means creating a new set of method statements for the same method signature (name, number of parameters and parameter types). Method overriding is seen when a superclass and a subclass have the same named method with the identical method inputs. It is said that the method in the subclass overrides method in the superclass.

Inheritance: Method Overload Method overloading simply means that a class has several methods with the same name but different input parameters.

Inheritance: Example Rectangle Box Box height : double Box() Box(double, double, double) setDimension (double, double, double) : void getHeight() : double calcArea() : double calcVolume() : double toString() : String Rectangle length : double width : double Rectangle() Rectangle(double, double) setDimension (double, double): void getLength(): double getWidth(): double calcArea(): double calcPerimeter(): double toString(): String Rectangle Box

Superclass: Rectangle Inheritance: Example

Inheritance: Example Rectangle Box Box height : double Box() Box(double, double, double) setDimension (double, double, double): void getHeight(): double calcArea(): double calcVolume(): double toString(): String Rectangle Box

Subclass: Box

Inheritance: Example Output ? We need an application class. Rectangle Box

Application class ?