Chapter 12 Advanced Inheritance

Slides:



Advertisements
Similar presentations
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.
Advertisements

Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
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.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Chapter 10 Classes Continued
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Programming Languages and Paradigms Object-Oriented Programming.
COP 3003 Object-Oriented Programming - Polymorphism Dr. Janusz Zalewski, Fall 2013 Prepared by Dr Dahai Guo.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 Chapter 9a Abstract Classes & Dynamic Binding. 2 Abstract Classes All classes so far have been concrete classes –Classes that can be used to create.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces and Inner Classes
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.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CH10 Supplementary Material Prepared by Fatimah Alakeel Oct 2010.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
Modern Programming Tools And Techniques-I
Polymorphism, Abstract Classes & Interfaces
Inheritance and Polymorphism
Understanding Inheritance
Java Programming Language
Polymorphism, Abstract Classes & Interfaces
Inheritance Inheritance is a fundamental Object Oriented concept
Java Programming, Second Edition
Inheritance.
Chapter 9 Carrano Chapter 10 Small Java
Advanced Inheritance Concepts
Topics OOP Review Inheritance Review Abstract Classes
Presentation transcript:

Chapter 12 Advanced Inheritance Jim Burns

Creating and Using Abstract Classes Child classes are more specific than their parents When you create a child class, it inherits all the general attributes you need Thus you must create only the new, more specific attributes Superclasses contain the features that are shared by their subclasses For example, the members of the Dog class are shared by the Poodle and Spaniel subclasses

Parent classes… Are sometimes so general that you never intend to create any specific instances of the class An abstract class is one from which you cannot create any concrete instantiations, but from which you can inherit Abstract classes usually have one or more empty abstract methods

Abstract Classes abstract You use the keyword ______ when you declare an abstract class abstract

Abstract methods abstract Have no body… No braces, and no method statements. When you create an abstract method, you use the keyword _____ abstract

public abstract class Animal { private String nameOfAnimal; public abstract void speak(); public String getAnimalName() return nameOfAnimal; } public void setAnimalName(String name) nameOfAnimal = name;

Note… If you declare any method to be an abstract method, you must also declare its class to be _______. abstract

For ____ classes You cannot place a statement such as Animal myPet = new Animal(“Murphy”); You create an abstract class such as Animal only so you can extend it.

Example of extending an abstract class public class Dog extends Animal { public void speak() System.out.println(“Woof!”); } The speak() method within the Dog class is required because the abstract, parent Animal class contains an abstract speak() method. You can code any statements you want within the Dog speak() method.

Public class Cow extends animal { public void speak() System.out.println(“Moo!”); } THE COW CLASS

Public class Snake extends animal { public void speak() System.out.println(“Ssss!”); } THE SNAKE CLASS

public class UseAnimals { public static void main(String[] args) Dog myDog = new Dog(); Cow myCow = new Cow(); Snake mySnake = new Snake(); myDog.setAnimalName("My dog Murphy"); myCow.setAnimalName("My cow Elsie"); mySnake.setAnimalName("My snake Sammy"); System.out.print(myDog.getAnimalName() + " says "); myDog.speak(); System.out.print(myCow.getAnimalName() + " says "); myCow.speak(); System.out.print(mySnake.getAnimalName() + " says "); mySnake.speak(); }

The above code produces the following at the command prompt: C:\Java>java UseAnimals My dog Murphy says Woof! My cow Elsie says Moo! My snake Sammy says Ssss! C:\Java>

Using Dynamic Method Binding An instantiation of a subclass “is a” superclass object. Every SalariedEmployee “is an” employee; every Dog “is an” animal The opposite is not true—an Animal is not a Dog Because every subclass object “is a” superclass member, you can convert subclass objects to superclass objects

More on dynamic method binding Even though you cannot instantiate any objects of an abstract class, you can indirectly create a reference to a superclass abstract object A reference is not an object, but it points to a memory address When you create a reference, you do not use the keyword new; instead, you create a variable name in which you can hold the memory address of a concrete object Even though a reference to an abstract superclass object is not concrete, you can store a reference to a concrete subclass object there

An example of the use of reference public class AnimalReference { public static void main(String[] args) Animal ref; ref = new Cow(); ref.speak(); ref = new Dog(); }

Recall from chapter 11… That you can use the instanceof keyword to determine whether an object is an instance of any class in its hierarchy. For example, using the Animal and Dog classes, both of the following are true if myPoodle is a dog object: myPoodle instanceof Animal myPoodle instanceof Dog

Polymorphic behavior The example above demonstrates polymorphic behavior After the variable ref is assigned an address, the ref.speak() method calls the correct speak() method An application’s ability to select the correct subclass method is known as dynamic method binding When the application executes, the correct method is attached to the application based on the current changing content

Using a Superclass as a Method Parameter Dynamic method binding is most useful when you want to create a method that has one or more parameters that might be one of several types In the following, the header for the talkingAnimal() method in Figure 12-9 accepts any type of Animal argument The talkingAnimal() method can be used in programs that contain Dog objects, Cow objects or objects of any class that descends from Animal

public class TalkingAnimalDemo { public static void main(String[] args) Dog dog = new Dog(); Cow cow = new Cow(); dog.setAnimalName("Ginger"); cow.setAnimalName("Molly"); talkingAnimal(dog); talkingAnimal(cow); } public static void talkingAnimal(Animal animal) System.out.println("Come one come all"); System.out.println("See the amazing talking animal!"); System.out.println(animal.getAnimalName() + " says"); animal.speak(); System.out.println("***************");

The above code produces the following at the command prompt: C:\Java>java TalkingAnimalDemo Come one come all See the amazing talking animal! Ginger says Woof! **************** See the maxing talking animal! Molly says Moo! ***************** C:\Java>

Creating Arrays of Sublcass Objects It can be convenient to create an array of generic Animal references An Animal array might contain individual elements that are Dog, Cow, or Snake objects The following statement creates an array of three Animal references Animal[] ref = new Animal[3]; This statement reserves enough computer memory for three Animal objects named ref[0], ref[1], and ref[2] The statement does not actually instantiate Animals as Animals are abstract

public class AnimalArrayDemo { public static void main(String[] args) Animal[] ref = new Animal[3]; ref[0] = new Dog(); ref[1] = new Cow(); ref[2] = new Snake(); for(int x = 0; x < 3; ++x) ref[x].speak(); }

The above code produces the following at the command prompt: C:\Java>java AnimalArrayDemo Woof! Moo! Ssss! C:\Java>

Using the Object Class and Its Methods The toString() Method The equals() Method

Using the Object Class and Its Methods Every class in Java is actually a subclass, except one When you define a class, if you do not explicitly extend another class, your class is an extension of the Object class The Object class is defined in the java.lang package, which is imported automatically every time you write a program; it includes methods that you can use or override as you see fit

Using the toString() Method The Object class toString() method converts an Object into a string that contains information about the Object If you do not create a toString() method for a class, you can use the superclass version of the toString() method

public abstract class Animal { private String nameOfAnimal; public abstract void speak(); public String getAnimalName() return nameOfAnimal; } public void setAnimalName(String name) nameOfAnimal = name; public class Dog extends Animal public void speak() System.out.println("Woof!"); Public class DisplayDog public static void main(String[ ] args) Dog myDog = new Dog(); string dogString = myDog.toString(); System.out.println(dogString);

Public class DisplayDog { public static void main(String[ ] args) Dog myDog = new Dog(); string dogString = myDog.toString(); System.out.println(dogString); }

The above produces the following output at the command Prompt C:\Java>java DisplayDog Dog@19821f C:\Java> The output is the word Dog ‘at’ 19821f, which is a hexadecimal number representing the reference

It is better to write your… own toString() method to override the one supplied so you can, among other purposes, debug a program The following example shows a BankAccount class that contains a mistake in the pink line

public class BankAccount { private int acctNum; private double balance; public BankAccount(int num, double bal) acctNum = num; balance = num; // Mistake! Should be balance = bal } public String toString() String info = "BankAccount acctNum = " + acctNum + " Balance = $" + balance; return info; public boolean equals(BankAccount secondAcct) boolean result; if(acctNum == secondAcct.acctNum && balance == secondAcct.balance) result = true; else result = false; return result;

public class TestBankAccount { public static void main(String[] args) BankAccount myAccount = new BankAccount(123, 4567.89); System.out.println(myAccount.toString()); }

The above produces the following output at the Command Prompt C:\Java>java TestBankAccount BankAccount accNum = 123 Balance = $123.00 C:\Java

The advantage of using the toString() toString() is Java’s universal name for a method that converts an object’s relevant details into String format As you use other programmers classes, you can hope that they have provided a toString() method that provides output that you would want to see.

Using the equals() Method The Object class equals() method returns a boolean value indicating whether the objects are equal if(someObject.equals(someOtherObjectOfTheSameType)) system.out.println( “The objects are equal”); Two objects are equal only if they have the same memory address

public class CompareAccounts { public static void main(String[] args) BankAccount acct1 = new BankAccount(1234, 500.00); BankAccount acct2 = new BankAccount(1234, 500.00); if(acct1.equals(acct2)) System.out.println("Accounts are equal"); else System.out.println("Accounts are not equal"); }

Command Prompt output C:\Java>java CompareAccounts Accounts are not equal C:\Java>

If you want two bank accounts… To be equal if they have the same account number and balance, then you must write your own equals() method…

public class BankAccount { private int acctNum; private double balance; public BankAccount(int num, double bal) acctNum = num; balance = num; // Mistake! Should be balance = bal } public String toString() String info = "BankAccount acctNum = " + acctNum + " Balance = $" + balance; return info; public boolean equals(BankAccount secondAcct) boolean result; if(acctNum == secondAcct.acctNum && balance == secondAcct.balance) result = true; else result = false; return result;

Example of your own equals() public boolean equals(BankAccount secondAcct) { boolean result; if(acctNum == secondAcct.acctNum && balance == secondAcct.balance) result = true; else result = false; return result; }

Command Prompt output C:\Java>java CompareAccounts Accounts are equal C:\Java>

Using Inheritance to Achieve Good Software Design When new car models are created, not every feature and function is redesigned from scratch With inheritance, you can reuse existing superclasses to create good designs quickly

Advantages of Inheritance Subclass creators save development time because much of the code needed for the class has already been written Subclass creators save testing time because the superclass code has already been tested and used in a variety of situations

More advantages… Programmers who create or use new subclasses already understand how the superclass works, so the time it takes to learn the new class features is reduced When you create a new subclass in Java, neither the superclass source code nor the superclass bytecode is changed

Creating and Using Interfaces Some programming languages like C++ allow for a subclass to inherit from more than one superclass The ability to inherit from more than one class is called multiple inheritance Multiple inheritance is a difficult concept—to which superclass should super refer to? Sooo, multiple inheritance is disallowed in Java

Interfaces Java provides an alternative to multiple inheritance—an Interface An interface looks much like a class, except that all of its methods are implicitly public and abstract, and all of its data items are implicitly public, static and final When you create a class that uses an interface, you include the keyword implements and the interface name in the class header This notation requires class objects to include code for every method in the interface that has been implemented

More on Interfaces Whereas using extends allows a subclass to use nonprivate, nonoverriden members of its parent’s class, implements requires the subclass to implement its own version of each method in the interface In the following, a worker interface is defined that contains the single method called work() When any class implements worker, it must also include a work() method

Public abstract class animal { private String nameOfAnimal; public abstract void speak(); public String getAnimalName() return nameOfanimal; } public void setAnimalName(String name) nameOfanimal = name; Public class Dog extends Animal public void speak() System.out.println(“woof!”); Public interface Worker public void work();

public class WorkingDog extends Dog implements Worker { private int hoursOfTraining; public void setHoursOfTraining(int hrs) hoursOfTraining = hrs; } public int getHoursOfTraining() return hoursOfTraining; public void work() speak(); System.out.println("I am a dog who works"); System.out.println("I have " + hoursOfTraining + " hours of professional training!");

public class DemoWorkingDogs { public static void main(String[] args) WorkingDog aSheepHerder = new WorkingDog(); WorkingDog aSeeingEyeDog = new WorkingDog(); aSheepHerder.setAnimalName("Simon, the Border Collie"); aSeeingEyeDog.setAnimalName("Sophie, the German Shepherd"); aSheepHerder.setHoursOfTraining(40); aSeeingEyeDog.setHoursOfTraining(300); System.out.println(aSheepHerder.getAnimalName() + " says "); aSheepHerder.speak(); aSheepHerder.work(); System.out.println(); System.out.println(aSeeingEyeDog.getAnimalName() + " says "); aSeeingEyeDog.speak(); aSeeingEyeDog.work(); }

Command Prompt output C:\Java>java demoWorkingDogs Simon, the Border Collie says Woof! I am a dog who works I have 40 hours of professional training! Sophie, the German Shepherd says I have 300 hours of professional training! C:\Java>

More on Interfaces Abstract classes and interfaces are similar in that you cannot instantiate concrete objects from either one Abstract classes differe from interfaces because abstract classes can contain nonabstract methods, but all methods within and interface must be abstract. A class can inherit from only one abstract superclass, but it can implement any number of iterfaces

Creating Interfaces to Store Related Constants Interfaces can contain data fields, but the must be public, static and final The purpose in creating an interface containing constants is to provide a set of data that a number of classes can use without having to re-declare the values An example follows

public interface PizzaConstants { public static final int SMALL_DIAMETER = 12; public static final int LARGE_DIAMETER = 16; public static final double TAX_RATE = 0.07; public static final String COMPANY = "Antonio's Pizzeria"; }

public class PizzaDemo implements PizzaConstants { public static void main(String[] args) double specialPrice = 11.25; System.out.println("Welcome to " + COMPANY); System.out.println("We are having a special offer:\na " + SMALL_DIAMETER + " inch pizza with four ingredients\nor a " + LARGE_DIAMETER + " inch pizza with one ingredient\nfor only $" + specialPrice); System.out.println("With tax, that is only $" + (specialPrice + specialPrice * TAX_RATE)); }

Command Prompt output C:\Java>javaPizzaDemo Welcome to Antonio’s Pizzeria We are having a special offer: A 12 inch pizza with four ingredients Or a 16 inch pizza with one ingredient For only $11.25 With tax, that is only $12.0375 C:\Java>

Creating and Using Packages You know how to import packages into your programs Java.lang package is automatically imported into every program your write A package is a named collection of classes When you create your own classes, you can place them in packages so that you can easily import related classes into new programs

More on packages Creating packages encourages others to reuse software because it makes it convenient to import many related classes at once When you create classes for others to use, you do not want to provide the users with your source code in the files with .java extensions

So you compile your classes You are creating compiled classes with the .class extensions The .class files are the files you place in a package so other programmers can import them You include a package statement at the beginning of your class file to place the compiled code into the indicated folder

The package statement package com.course.animals; Indicates that the compiled file should be placed in a folder named com.course.animals The compiled program goes into an animals folder within the course folder within the com folder The package statement should be the first such statement and should be outside the class definition