Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.

Similar presentations


Presentation on theme: "Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object."— Presentation transcript:

1

2 Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object class Polymorphism Abstract Classes and Abstract Methods Interfaces

3

4 Inheritance The Concept: Inheritance allows a new class to extend an existing class. The new class inherits the public methods and fields of the class that it extends.

5 An example of inheritance Human Class ----------------------------------- - double Height - double Weight - String Name - int Gender - Date Data of Birth ----------------------------------- + ComputeAge(void) : int + set and get for all the Fields Woman extends Human ----------------------------------- - boolean isPregnant - boolean hasPlayedSoftBall - boolean pageantBefore - boolean cheerLeader ----------------------------------- + int set and get for all class fields + printInfo() : void Man extends Human ----------------------------------- -boolean hasPlayedFootball -boolean hasPlayedBaseball -hasBeardAndMustache ----------------------------------- + set and get for all the Fields + printInfo(void) : void

6 Let’s create those three classes Human Class Woman Class Man Class See Inheritance Project

7 Question of the Day Inheritance: “is a” To know if you can use inheritance in your class, ask yourself if your class “is a” of the inherited class Examples: A poodle is a dog A flower is a plant A rectangle is a shape A car is a motor??? How do we know what can be inherited?

8

9 Another Example of Inheritance Situation The final grade of students is based on a set of graded activities: All activities generate a score (0-100 points) Each activity has a different way of computing its score Each activity has its weight percentage into the final course grade Graded ActivityHow grade is appliedPercentage of final grade LaboratoryNumber of correctly completed labs25% Midterm ExamNumber of corrected answers35% Final examNumber of correct answers40%

10 The inheritance tree Graded Activity Class Lab Activity Class Midterm Exam Class Midterm Exam Class Final Exam Class Final Exam Class

11 Grade Activity Class ----------------------------------- - score : double - percentage : double - activityType : String ----------------------------------- + setScore(s : double) : void + getScore() : double + other setters and getters LaboratoryActivity ----------------------------------- - completedLabs : int - numberOfLabs : int ----------------------------------- + computeScore() Midterm Activity ----------------------------------- - numberOfQuestions : int - numberOfMisses : int ----------------------------------- + computeScore() + getActivityScore() : double + getPercentage FinalExame Activity ----------------------------------- - numberOfQuestions : int - numberOfMisses : int ----------------------------------- + computeScore() + getActivityScore() : double + getPercentage Midterm Activity ----------------------------------- + MidtermActivity( int numberOfMisses, int numberOfQuestions) - sets the percentage - sets the activityType FinalExam Activity ----------------------------------- + FinalExamActivity( int numberOfMisses, int numberOfQuestions) - sets the percentage - sets the activityType Exams Activity ----------------------------------- - numberOfQuestions : int - numberOfMisses : int ----------------------------------- + computeScore() : void + setNumberOfQuestions() + getNumberOfQuestions() + other setters and getters

12

13 Let’s refresh our memory about Constructors What does a constructor do? When is a contructor called?

14 Constructors are created when you use the “new” operation to create new objects from a class blue print ArrayList listOfStudents = new ArrayList( ); You can use constructors to initialize class fields and automatically run methods to initialize whatever is necessary Example: see LaboratoryActivity class Does every class have a constructor? Yes. If you do not create one, Java will create a default contructor with no input arguments public DefaultConstructor( ) { }

15 Which constructor is called? When you create a new object from a sub-class, like FinalExamActivity, which constructor is called? Is the constructor of the super class called when creating a sub-class object? Hint: Think about in the case that the super class initializes some fields Let’s do a test, let’s modify the GradeActivity project and see what happens…

16 As you know, a class can have multiple constructors Different signatures (input arguments) If your sub-class needs to execute a specific constructor of the super class then just call it from the sub-class constructor like this: Public SubClass2( ) { super(10); // do your stuff here } If a super class has not default constructor, the sub-class MUST call the super class constructor in its (sub-class) constructor!

17

18 11-18 Inheritance, Fields and Methods Members of the superclass that are marked private: are not inherited by the subclass, exist in memory when the object of the subclass is created may only be accessed from the subclass by public methods of the superclass. Members of the superclass that are marked public: are inherited by the subclass, and may be directly accessed from the subclass.

19 11-19 Inheritance, Fields and Methods When an instance of the subclass is created, the non-private methods of the superclass are available through the subclass object. FinalExam exam = new FinalExam(); exam.setScore(85.0); System.out.println("Score = " + exam.getScore()); Non-private methods and fields of the superclass are available in the subclass. setScore(newScore); See Inheritance Project

20

21 Important Points to Remember A sub class can: Call methods from the super class. These methods are inherited by the sub class Can create new methods in its body that the super class does not have These new methods cannot be called by the super class Override existing methods from the super class When calling these methods, Java will use the sub class methods instead of the one from super class

22 11-22 Overriding Superclass Methods Both overloading and overriding can take place in an inheritance relationship. Overriding can only take place in an inheritance relationship. Example: See Example next slide SuperClass3.java, SuperClass3.java SubClass3.java, SubClass3.java ShowValueDemo.java

23

24

25 11-25 Preventing a Method from Being Overridden The final modifier will prevent the overriding of a superclass method in a subclass. public final void message() If a subclass attempts to override a final method, the compiler generates an error. This ensures that a particular superclass method is used by subclasses rather than a modified version of it.

26 Example of Final Methods and Fields double i = Math.PI; public static final double PI = 3.14159265358979323846; You do not want anyone to override methods like SINE and COSINE public static final double sin(double a)

27

28 11-28 Protected Members Protected members of class: may be accessed by methods in a subclass, and by methods in the same package as the class. Example: GradedActivity2.java FinalExam2.java ProtectedDemo.java

29 11-29 Access Specifiers ModifierClassPackageSubclassWorld public ✔✔✔✔ protected ✔✔✔✘ no modifier ✔✔✘✘ private ✔✘✘✘

30

31 11-31 The Object Class All Java classes are directly or indirectly derived from a class named Object. Object is in the java.lang package. Any class that does not specify the extends keyword is automatically derived from the Object class. public class MyClass { // This class is derived from Object. } Ultimately, every class is derived from the Object class.

32 11-32 The Object Class Because every class is directly or indirectly derived from the Object class: every class inherits the Object class’s members. example: toString and equals. In the Object class, the toString method returns a string containing the object’s class name and a hash of its memory address. The equals method accepts the address of an object as its argument and returns true if it is the same as the calling object’s address. Example: ObjectMethods.javaObjectMethods.java

33

34 The Concept of Polymorphism Shape Rectangle Circle area() perimeter() area() perimeter() area() perimeter() Circle and Rectangle are concrete classes with their own separate implementations of the methods area() and Perimeter() Shape is an abstract class with no implementation of area() and perimeter()

35 public abstract class Shape { protected String shapeName; public Shape(String name) { shapeName = name; } public abstract double area( ); public abstract double perimeter( ); public String toString( ) { return shapeName; } } The Concept of Polymorphism

36 public class Rectangle extends Shape { protected double length, width; public Rectangle(double len, double wid { super(“Rectangle”); length = len; width = wid; } public double area() { return length * width; } public double perimeter() { return 2.0 * (length + width); } } public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area( ) { return Math.PI * radius * radius; } public double perimeter( ) { return 2.0 * Math.PI * radius; } }

37 A Listof Shapes A container of Shape objects will execute their own area and perimeter methods The Concept of Polymorphism

38 public class ShapeShifter { public static void main (String [ ] args) { Shape [ ] shapeList = new Shape[5]; shapeList[0] = new Circle(3.0); shapeList[1] = new Rectangle(3.0, 4.0); shapeList[2] = new Rectangle(2.5, 7.5); shapeList[3] = new Circle(2.5); shapeList[4] = new Square(5.0); for (int i = 0; i < shapeList.length; i++) { System.out.print (shapeList[i].toString( ) + “ ”); System.out.print (shapeList[i].area( ) + “ ”); System.out.println (shapeList[i].perimeter( )); } } } Create an array to hold objects of (derived from) class Shape Create objects of the derived classes and put them in shapeList Iterate through the list and show area and perimeter of shapes Each derived class object executes its own area and perimeter methods The Concept of Polymorphism

39

40 11-40 Abstract Class An abstract class cannot be instantiated, but other classes are derived from it. An Abstract class serves as a superclass for other classes. A class becomes abstract when you place the abstract key word in the class definition. public abstract class ClassName

41 11-41 Abstract Methods An abstract method has no body and must be overridden in a subclass. An abstract method is a method that appears in a superclass, but expects to be overridden in a subclass. Example: See next page Student.java, CompSciStudent.java, CompSciStudentDemo.java Student.javaCompSciStudent.javaCompSciStudentDemo.java

42 public abstract class Shape { protected String shapeName; public Shape(String name) { shapeName = name; } public abstract double area( ); public abstract double perimeter( ); public String toString( ) { return shapeName; } public class Rectangle extends Shape { protected double length, width; public Rectangle(double len, double wid { super(“Rectangle”); length = len; width = wid; } public double area() { return length * width; } public double perimeter() { return 2.0 * (length + width); } public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area() { return Math.PI * radius * radius; } public double perimeter() { return 2.0 * Math.PI * radius; }

43 11-43 Abstract Methods Notice that the key word abstract appears in the header, and that the header ends with a semicolon. public abstract void setValue(int value); Any class that contains an abstract method is automatically abstract. If a subclass fails to override an abstract method, a compiler error will result. Abstract methods are used to ensure that a subclass implements the method.

44 Another Examples of the need for abstract classes You made a game that all the animals must jump and make noises However each animal has a different way of jumping and roar. So you abstract the jump and noise methods and whoever creates a new animal must implement those methods You create a pizza recipe program that tells you the steps for creating different types of pizza Since each pizza has different toppings, you abstract the listOfIngridients() method

45

46 11-46 Fields in Interfaces An interface can contain field declarations: all fields in an interface are treated as final and static. Because they automatically become final, you must provide an initialization value. public interface Doable { int FIELD1 = 1, FIELD2 = 2; (Method headers...) } Any class that implements this interface has access to these variables.

47 11-47 Implementing Multiple Interfaces A class can be derived (extended ) from only one superclass. Java allows a class to implement multiple interfaces. When a class implements multiple interfaces, it must provide the methods specified by all of them. To specify multiple interfaces in a class definition, simply list the names of the interfaces, separated by commas, after the implements key word. public class MyClass implements Interface1, Interface2, Interface3

48 11-48 Interfaces in UML GradedActivity RelatableFinalExam3 A dashed line with an arrow indicates implementation of an interface.

49 11-49 Polymorphism with Interfaces Java allows you to create reference variables of an interface type. An interface reference variable can reference any object that implements that interface, regardless of its class type. This is another example of polymorphism. Example: RetailItem.java CompactDisc.java DvdMovie.java PolymorphicInterfaceDemo.java

50 11-50 Polymorphism with Interfaces In the example code, two RetailItem reference variables, item1 and item2, are declared. The item1 variable references a CompactDisc object and the item2 variable references a DvdMovie object. When a class implements an interface, an inheritance relationship known as interface inheritance is established. a CompactDisc object is a RetailItem, and a DvdMovie object is a RetailItem.

51 11-51 Polymorphism with Interfaces A reference to an interface can point to any class that implements that interface. You cannot create an instance of an interface. RetailItem item = new RetailItem(); // ERROR! When an interface variable references an object: only the methods declared in the interface are available, explicit type casting is required to access the other methods of an object referenced by an interface reference.


Download ppt "Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object."

Similar presentations


Ads by Google