Introduction to Java 2 Programming

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

1 Inheritance Classes and Subclasses Or Extending a Class.
Introduction to Java 2 Programming Lecture 5 Quick Recap; Error-handling.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
General OO Concepts Objectives For Today: Discuss the benefits of OO Programming Inheritance and Aggregation Abstract Classes Encapsulation Introduce Visual.
Chapter 1 Inheritance University Of Ha’il.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 211 Inheritance AAA.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
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
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
ITEC200 – Week03 Inheritance and Class Hierarchies.
 In inheritance the child (subclass) chooses its parent (superclass)  Remember - only public or “protected” methods and variables are inherited  Should.
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 and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics 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.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Inheritance in the Java programming language J. W. Rider.
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 and Access Control CS 162 (Summer 2009)
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
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.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Lecture 12 Inheritance.
Inheritance and Polymorphism
An Introduction to Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
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.
Advanced Programming Behnam Hatami Fall 2017.
Overriding Methods & Class Hierarchies
Inheritance and Polymorphism
Chapter 7 Inheritance.
Presentation transcript:

Introduction to Java 2 Programming Lecture 5 Inheritance

Overview Inheritance …and Encapsulation …and Constructors …and Methods Including overriding and overloading Controlling Inheritance

Quick Recap Inheritance defines parent-child relationships Base (or super) class, and derived (or sub-) class Child inherits all functionality of its parent Typically add new methods and member variables One of the basic features of all OO languages Already encountered it in Robocode All your robots extend a provided Robot base class All robocode events extend an Event base class You can extend almost any object With a couple of extensions as we’ll see…

Using Inheritance Use the extends keyword in the class definition: public class MyRobot extends Robot { } A class can only extend one base class Unlike C++ Java doesn’t allow multiple inheritance All Java classes extend a common base class (java.lang.Object) Automatically assumed by the compiler, unless you say otherwise Provides some basic functionality, e.g. toString() and equals() public class Calculator extends Object {

Inheritance and Encapsulation Sub-classes inherit all their superclass member variables But may not be able to access them directly! The visibility modifiers, public, protected, and private apply Only public and protected are accessible Private member variables of a base class cannot be altered by a sub-class (except via a method) Tip: Try to avoid breaking encapsulation by making variables private, unless you’re expecting the class to “have children”

Inheritance and Encapsulation public class Person { private String _name; private String _email; //can be access by sub-classes protected int _salary; public String getName() {…} public String setName() {…} }

Constructors Revisited Constructors can call one another Allows initialisation code to be kept in one place (not duplicated between constructors) Use the this keyword to call another constructor in the same class Must be first line in the constructor public class Bookmark { public Bookmark(String url) { this( new URL(url) ); } public Bookmark(URL url) { //other initialisation code

Inheritance and Constructors An class must ensure that its parent is properly initialised, by calling one of its constructors Use the super keyword Even if a constructor isn’t explicitly called a call to the default constructor is added by compiler Base class constructors are called first Inheritance happens from the top down …ancestors, parent, child…

Constructors public class Parent { private String msg; public Parent() {} public Parent(String message) { msg = message; } public class Child extends Parent {   public Child()  {    super("Parent message");  public class OtherChild extends Parent {

Method Overloading A Java class can define several methods with the same name, so long as the parameters are different, the return type is the same public int doSomething(String s, String s2); public int doSomething(String s); public int doSomething(int x, int y); Java determines the correct method to call by checking the parameters Useful to provide variants of a method that work on different types of object Typically one method does all the work, and the others call it As with constructors, this collects common code into a single method

Method Overriding A sub-class can define a method with the same name and parameters as as base class Known as overriding Useful when some aspect of the base class behaviour must be altered To completely change the implementation, just define a new version (in the child) To partially change the implementation use the super keyword to refer to the parents original implementation

Inheritance and Methods What happens when we call a method? The JVM tries to find the implementation of that method and then execute the code Starts searching with the objects class, then works upward to its parent…its parent’s parent…etc, etc. Searching for methods works from the bottom-up Reverse of how constructors are called Also explains how a sub-class can substitute its own behaviour for a base class JVM finds that first.

Worked Example In an E-Commerce system we might have a class responsible for calculating prices e.g:  public class Pricer { public float calculatePrice(Product p) {  //implementation details irrelevant for example } The Product parameter lets the Pricer calculate the price

Worked Example Assume we want to extend this functionality so that the calculation also includes tax (i.e. adding on VAT). US purchases don't include tax, but UK ones do, so we can't just rewrite the original method. Instead we create a subclass, called UKPricer that does the extra work.  public class UKPricer extends Pricer { public float calculatePrice(Product p) {  //this implementation will also add on VAT… }

Worked Example Ideally we want to reuse the code in the base class, as all we need to do is add on the extra 17.5% to the final price. We can do better than copy-and-paste using super… public class UKPricer extends Pricer { public float calculatePrice(Product p) {    //call the superclass method   float withoutTax = super.calculatePrice(p);   float tax = withoutTax * 17.5 / 100;  return withoutTax + tax; }

Controlling Inheritance – Restricting Inheritance can be restricted using the final keyword Applies to both methods and classes A final class cannot be extended A final method cannot be overridden public final class MyClass { } public class OtherClass { public final int aMethod() { … }

Controlling Inheritance – Enforcing Inheritance can be forced by using the abstract keyword Again applies to both methods and classes An abstract class must be extended, cannot be used to create objects An abstract method must be overrided by a sub-class A class with at least one abstract method must be declared abstract public abstract class SomeOtherClass { public int aMethod() { … } public abstract void otherMethod(); }