Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 12 Advanced Inheritance

Similar presentations


Presentation on theme: "Chapter 12 Advanced Inheritance"— Presentation transcript:

1 Chapter 12 Advanced Inheritance
Jim Burns

2 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

3 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

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

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

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

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

8 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.

9 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.

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

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

12 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(); }

13 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>

14 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

15 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

16 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(); }

17 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

18 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

19 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

20 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("***************");

21 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>

22 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

23 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(); }

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

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

26 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

27 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

28 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);

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

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

31 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

32 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;

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

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

35 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.

36 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

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

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

39 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…

40 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;

41 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; }

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

43 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

44 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

45 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

46 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

47 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

48 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

49 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();

50 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!");

51 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(); }

52 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>

53 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

54 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

55 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"; }

56 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)); }

57 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 $ C:\Java>

58 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

59 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

60 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

61 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


Download ppt "Chapter 12 Advanced Inheritance"

Similar presentations


Ads by Google