SlideShare a Scribd company logo
Chapter 10
Object Oriented Programming Concepts
(Inheritance)
Chapter Topics (1 of 2)
10.1 What Is Inheritance?
10.2 Calling the Superclass Constructor
10.3 Overriding Superclass Methods
10.4 Protected Members
10.5 Chains of Inheritance
10.6 The Object Class
Chapter Topics (2 of 2)
10.7 Polymorphism
10.8 Abstract Classes and Abstract Methods
10.9 Interfaces
10.10 Anonymous Classes
10.1 What is Inheritance?
Generalization versus Specialization
• Real-life objects are typically specialized versions of other more general objects.
• The term “insect” describes a very general type of creature with numerous characteristics.
• Grasshoppers and bumblebees are insects
– They share the general characteristics of an insect.
– However, they have special characteristics of their own.
▪ grasshoppers have a jumping ability, and
▪ bumblebees have a stinger.
• Grasshoppers and bumblebees are specialized versions of an insect.
Inheritance (1 of 2)
The “is a” Relationship (1 of 2)
• The relationship between a superclass and an inherited class
is called an “is a” relationship.
– A grasshopper “is a” insect.
– A poodle “is a” dog.
– A car “is a” vehicle.
• A specialized object has:
– all of the characteristics of the general object, plus
– additional characteristics that make it special.
• In object-oriented programming, inheritance is used to create
an “is a” relationship among classes.
The “is a” Relationship (2 of 2)
• We can extend the capabilities of a class.
• Inheritance involves a superclass and a subclass.
– The superclass is the general class and
– the subclass is the specialized class.
• The subclass is based on, or extended from, the superclass.
– Superclasses are also called base classes, and
– subclasses are also called derived classes.
• The relationship of classes can be thought of as parent
classes and child classes.
Inheritance (2 of 2)
• The subclass inherits fields and methods from the superclass
without any of them being rewritten.
• New fields and methods may be added to the subclass.
• The Java keyword, extends, is used on the class header to
define the subclass.
The GradedActivity Example
Example:
• GradedActivity.java,
• GradeDemo.java,
• FinalExam.java,
• FinalExamDemo.java
Inheritance in UML Diagrams
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.
Inheritance, Fields and Methods (2 of 2)
• When an instance of the subclass is created, the non-
private methods of the superclass are available through
the subclass object.
• Non-private methods and fields of the superclass are
available in the subclass.
Inheritance and Constructors
• Constructors are not inherited.
• When a subclass is instantiated, the superclass default constructor is
executed first.
• Example:
– SuperClass1.java
– SubClass1.java
– ConstructorDemo1.java
The Superclass’s Constructor
• The super keyword refers to an object’s superclass.
• The superclass constructor can be explicitly called from the
subclass by using the super keyword.
• Example:
– Rectangle.java, Cube.java, CubeDemo.java
10.2 Calling the Superclass Constructor
• If a parameterized constructor is defined in the
superclass,
– the superclass must provide a no-arg constructor, or
▪ subclasses must provide a constructor, and
▪ subclasses must call a superclass constructor.
• Calls to a superclass constructor must be the first java
statement in the subclass constructors.
10.3 Overriding Superclass Methods (1 of 5)
• A subclass may have a method with the same signature as a superclass
method.
• The subclass method overrides the superclass method.
• This is known as method overriding.
• Example:
– GradedActivity.java, CurvedActivity.java, CurvedActivityDemo.java
10.3 Overriding Superclass Methods (2 of 5)
10.3 Overriding Superclass Methods (3 of 5)
• Recall that a method’s signature consists of:
– the method’s name
– the data types method’s parameters in the order that they appear.
• A subclass method that overrides a superclass method must have the same signature as the
superclass method.
• An object of the subclass invokes the subclass’s version of the method, not the superclass’s.
• The @Override annotation should be used just before the subclass method declaration.
– This causes the compiler to display a error message if the method fails to correctly
override a method in the superclass.
10.3 Overriding Superclass Methods (4 of 5)
• A subclass method can call the overridden superclass method via the
super keyword.
• There is a distinction between overloading a method and overriding a
method.
• Overloading is when a method has the same name as one or more
other methods, but with a different signature.
• When a method overrides another method, however, they both have
the same signature.
10.3 Overriding Superclass Methods (5 of 5)
• Both overloading and overriding can take place in an inheritance relationship.
• Overriding can only take place in an inheritance relationship.
• Example:
– SuperClass3.java,
– SubClass3.java,
– ShowValueDemo.java
Preventing a Method from Being Overridden
• The final modifier will prevent the overriding of a superclass
method in a subclass.
• 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.
10.4 Protected Members (1 of 2)
• Java provides a third access specification, protected.
• Protected members of class:
– may be accessed by methods in a subclass, and
– by methods in the same package as the class.
• A protected member’s access is somewhere between private
and public.
• Example:
– GradedActivity2.java
– FinalExam2.java
– ProtectedDemo.java
10.4 Protected Members (2 of 2)
• Using protected instead of private makes some tasks easier.
• However, any class that is derived from the class, or is in the same package, has
unrestricted access to the protected member.
• It is always better to make all fields private and then provide public methods for
accessing those fields.
• If no access specifier for a class member is provided, the class member is given
package access by default.
• Any method in the same package may access the member.
Access Specifiers
Access Modifier
Accessible to a subclass inside
the same package?
Accessible to all other classes
inside the same package?
default (no modifier) Yes Yes
Public Yes Yes
Protected Yes Yes
Private No No
Access Modifier
Accessible to a subclass outside
the package?
Accessible to all other classes
outside the package?
default (no modifier) No No
Public Yes Yes
Protected Yes No
Private No No
10.5 Chains of Inheritance
• Classes often are depicted graphically in a class hierarchy.
• A class hierarchy shows the inheritance relationships between
classes.
10.6 The Object Class (1 of 2)
• 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.
• Ultimately, every class is derived from the Object class.
10.6 The Object Class (2 of 2)
• 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.java
10.7 Polymorphism (1 of 4)
• A reference variable can reference objects of classes that are
derived from the variable’s class.
GradedActivity exam;
• We can use the exam variable to reference a GradedActivity
object.
• The GradedActivity class is also used as the superclass for the
FinalExam class.
• An object of the FinalExam class is a GradedActivity object.
10.7 Polymorphism (2 of 4)
• A GradedActivity variable can be used to reference a
FinalExam object.
• This statement creates a FinalExam object and stores the object’s
address in the exam variable.
• This is an example of polymorphism.
• The term polymorphism means the ability to take many forms.
• In Java, a reference variable is polymorphic because it can
reference objects of types different from its own, as long as those
types are subclasses of its type.
10.7 Polymorphism (3 of 4)
• Other legal polymorphic references:
• The GradedActivity class has three methods: setScore,
getScore, and getGrade.
• A GradedActivity variable can be used to call only those three
methods.
Polymorphism and Dynamic Binding
• If the object of the subclass has overridden a method in the
superclass:
– If the variable makes a call to that method the subclass’s version
of the method will be run.
• Java performs dynamic binding or late binding when a variable
contains a polymorphic reference.
• The Java Virtual Machine determines at runtime which method to
call, depending on the type of object that the variable references.
10.7 Polymorphism (4 of 4)
• It is the object’s type, rather than the reference type, that
determines which method is called.
• Example:
– Polymorphic.java
• You cannot assign a superclass object to a subclass
reference variable.
10.8 Abstract Classes
• An abstract class cannot be instantiated, but other
classes are derived from it.
• An Abstract class serves as a superclass for other
classes.
• The abstract class represents the generic or abstract
form of all the classes that are derived from it.
• A class becomes abstract when you place the abstract
key word in the class definition.
10.8 Abstract Methods (1 of 2)
• 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.
• An abstract method has only a header and no body.
• Example:
– Student.java, CompSciStudent.java,
CompSciStudentDemo.java
10.8 Abstract Methods (2 of 2)
• Notice that the key word abstract appears in the header,
and that the header ends with a semicolon.
• 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.
10.9 Interfaces (1 of 3)
• An interface is similar to an abstract class that has all abstract
methods.
– It cannot be instantiated, and
– all of the methods listed in an interface must be written elsewhere.
• The purpose of an interface is to specify behavior for other classes.
• It is often said that an interface is like a “contract,” and when a class
implements an interface it must adhere to the contract.
• An interface looks similar to a class, except:
– the keyword interface is used instead of the keyword class,
and
– the methods that are specified in an interface have no bodies, only
headers that are terminated by semicolons.
10.9 Interfaces (2 of 3)
• The general format of an interface definition:
• All methods specified by an interface are public by default.
• A class can implement one or more interfaces.
10.9 Interfaces (3 of 3)
• If a class implements an interface, it uses the implements
keyword in the class header.
• Example:
– GradedActivity.java
– Relatable.java
– FinalExam3.java
– InterfaceDemo.java
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.
• In this interface, FIELD1 and FIELD2 are final static int
variables.
• Any class that implements this interface has access to these
variables.
Implementing Multiple Interfaces
• A class can be derived 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.
Interfaces in UML
Polymorphism with Interfaces (1 of 3)
• 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
Polymorphism with Interfaces (2 of 3)
• 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.
Polymorphism with Interfaces (3 of 3)
• A reference to an interface can point to any class that
implements that interface.
• You cannot create an instance of an interface.
• 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.
Default Methods
• Beginning in Java 8, interfaces may have default methods.
• A default method is an interface method that has a body.
• You can add new methods to an existing interface without
causing errors in the classes that already implement the
interface.
• Example:
– Displayable.java
– Person.java
– InterfaceDemoDefaultMethod.java
10.10 Anonymous Inner Classes
• An inner class is a class that is defined inside another class.
• An anonymous inner class is an inner class that has no name.
• An anonymous inner class must implement an interface, or extend another class.
• Useful when you need a class that is simple, and to be instantiated only once in your
code.
• Example:
– IntCalculator.java
– AnonymousClassDemo.java

More Related Content

Similar to Object oriented programming java inheritance (20)

PPTX
Java chapter 5
Abdii Rashid
 
PPTX
Ch5 inheritance
HarshithaAllu
 
PDF
L5
lksoo
 
PPT
Polymorphism
Kumar
 
PPT
Eo gaddis java_chapter_09_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_09_5e
Gina Bullock
 
PPTX
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
PDF
Unit 2
Amar Jukuntla
 
PPT
JavaHTP6e_10.ppt
AmineAbdellatif1
 
PPTX
‫Chapter3 inheritance
Mahmoud Alfarra
 
PDF
java-06inheritance
Arjun Shanka
 
PPTX
Inheritance and Polymorphism
KartikKapgate
 
PPTX
Chapter 8.2
sotlsoc
 
PPTX
Core java oop
Parth Shah
 
PPT
Ap Power Point Chpt7
dplunkett
 
PPTX
Chapter 05 polymorphism extra
Nurhanna Aziz
 
PPTX
Chap3 inheritance
raksharao
 
PDF
Java How to Program 9th Edition Deitel Test Bank
vorfiatraba
 
PPT
PolyInterfaces.pptnowand tomoroooooooooo
mugabecharles
 
PPTX
Java presentation
Akteruzzaman .
 
Java chapter 5
Abdii Rashid
 
Ch5 inheritance
HarshithaAllu
 
L5
lksoo
 
Polymorphism
Kumar
 
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Eo gaddis java_chapter_09_5e
Gina Bullock
 
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
JavaHTP6e_10.ppt
AmineAbdellatif1
 
‫Chapter3 inheritance
Mahmoud Alfarra
 
java-06inheritance
Arjun Shanka
 
Inheritance and Polymorphism
KartikKapgate
 
Chapter 8.2
sotlsoc
 
Core java oop
Parth Shah
 
Ap Power Point Chpt7
dplunkett
 
Chapter 05 polymorphism extra
Nurhanna Aziz
 
Chap3 inheritance
raksharao
 
Java How to Program 9th Edition Deitel Test Bank
vorfiatraba
 
PolyInterfaces.pptnowand tomoroooooooooo
mugabecharles
 
Java presentation
Akteruzzaman .
 

Recently uploaded (20)

PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
GitOps_Without_K8s_Training simple one without k8s
DanialHabibi2
 
PPTX
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
GitOps_Without_K8s_Training simple one without k8s
DanialHabibi2
 
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Design Thinking basics for Engineers.pdf
CMR University
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Ad

Object oriented programming java inheritance

  • 1. Chapter 10 Object Oriented Programming Concepts (Inheritance)
  • 2. Chapter Topics (1 of 2) 10.1 What Is Inheritance? 10.2 Calling the Superclass Constructor 10.3 Overriding Superclass Methods 10.4 Protected Members 10.5 Chains of Inheritance 10.6 The Object Class
  • 3. Chapter Topics (2 of 2) 10.7 Polymorphism 10.8 Abstract Classes and Abstract Methods 10.9 Interfaces 10.10 Anonymous Classes
  • 4. 10.1 What is Inheritance? Generalization versus Specialization • Real-life objects are typically specialized versions of other more general objects. • The term “insect” describes a very general type of creature with numerous characteristics. • Grasshoppers and bumblebees are insects – They share the general characteristics of an insect. – However, they have special characteristics of their own. ▪ grasshoppers have a jumping ability, and ▪ bumblebees have a stinger. • Grasshoppers and bumblebees are specialized versions of an insect.
  • 6. The “is a” Relationship (1 of 2) • The relationship between a superclass and an inherited class is called an “is a” relationship. – A grasshopper “is a” insect. – A poodle “is a” dog. – A car “is a” vehicle. • A specialized object has: – all of the characteristics of the general object, plus – additional characteristics that make it special. • In object-oriented programming, inheritance is used to create an “is a” relationship among classes.
  • 7. The “is a” Relationship (2 of 2) • We can extend the capabilities of a class. • Inheritance involves a superclass and a subclass. – The superclass is the general class and – the subclass is the specialized class. • The subclass is based on, or extended from, the superclass. – Superclasses are also called base classes, and – subclasses are also called derived classes. • The relationship of classes can be thought of as parent classes and child classes.
  • 8. Inheritance (2 of 2) • The subclass inherits fields and methods from the superclass without any of them being rewritten. • New fields and methods may be added to the subclass. • The Java keyword, extends, is used on the class header to define the subclass.
  • 9. The GradedActivity Example Example: • GradedActivity.java, • GradeDemo.java, • FinalExam.java, • FinalExamDemo.java Inheritance in UML Diagrams
  • 10. 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.
  • 11. Inheritance, Fields and Methods (2 of 2) • When an instance of the subclass is created, the non- private methods of the superclass are available through the subclass object. • Non-private methods and fields of the superclass are available in the subclass.
  • 12. Inheritance and Constructors • Constructors are not inherited. • When a subclass is instantiated, the superclass default constructor is executed first. • Example: – SuperClass1.java – SubClass1.java – ConstructorDemo1.java
  • 13. The Superclass’s Constructor • The super keyword refers to an object’s superclass. • The superclass constructor can be explicitly called from the subclass by using the super keyword. • Example: – Rectangle.java, Cube.java, CubeDemo.java
  • 14. 10.2 Calling the Superclass Constructor • If a parameterized constructor is defined in the superclass, – the superclass must provide a no-arg constructor, or ▪ subclasses must provide a constructor, and ▪ subclasses must call a superclass constructor. • Calls to a superclass constructor must be the first java statement in the subclass constructors.
  • 15. 10.3 Overriding Superclass Methods (1 of 5) • A subclass may have a method with the same signature as a superclass method. • The subclass method overrides the superclass method. • This is known as method overriding. • Example: – GradedActivity.java, CurvedActivity.java, CurvedActivityDemo.java
  • 16. 10.3 Overriding Superclass Methods (2 of 5)
  • 17. 10.3 Overriding Superclass Methods (3 of 5) • Recall that a method’s signature consists of: – the method’s name – the data types method’s parameters in the order that they appear. • A subclass method that overrides a superclass method must have the same signature as the superclass method. • An object of the subclass invokes the subclass’s version of the method, not the superclass’s. • The @Override annotation should be used just before the subclass method declaration. – This causes the compiler to display a error message if the method fails to correctly override a method in the superclass.
  • 18. 10.3 Overriding Superclass Methods (4 of 5) • A subclass method can call the overridden superclass method via the super keyword. • There is a distinction between overloading a method and overriding a method. • Overloading is when a method has the same name as one or more other methods, but with a different signature. • When a method overrides another method, however, they both have the same signature.
  • 19. 10.3 Overriding Superclass Methods (5 of 5) • Both overloading and overriding can take place in an inheritance relationship. • Overriding can only take place in an inheritance relationship. • Example: – SuperClass3.java, – SubClass3.java, – ShowValueDemo.java
  • 20. Preventing a Method from Being Overridden • The final modifier will prevent the overriding of a superclass method in a subclass. • 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.
  • 21. 10.4 Protected Members (1 of 2) • Java provides a third access specification, protected. • Protected members of class: – may be accessed by methods in a subclass, and – by methods in the same package as the class. • A protected member’s access is somewhere between private and public. • Example: – GradedActivity2.java – FinalExam2.java – ProtectedDemo.java
  • 22. 10.4 Protected Members (2 of 2) • Using protected instead of private makes some tasks easier. • However, any class that is derived from the class, or is in the same package, has unrestricted access to the protected member. • It is always better to make all fields private and then provide public methods for accessing those fields. • If no access specifier for a class member is provided, the class member is given package access by default. • Any method in the same package may access the member.
  • 23. Access Specifiers Access Modifier Accessible to a subclass inside the same package? Accessible to all other classes inside the same package? default (no modifier) Yes Yes Public Yes Yes Protected Yes Yes Private No No Access Modifier Accessible to a subclass outside the package? Accessible to all other classes outside the package? default (no modifier) No No Public Yes Yes Protected Yes No Private No No
  • 24. 10.5 Chains of Inheritance • Classes often are depicted graphically in a class hierarchy. • A class hierarchy shows the inheritance relationships between classes.
  • 25. 10.6 The Object Class (1 of 2) • 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. • Ultimately, every class is derived from the Object class.
  • 26. 10.6 The Object Class (2 of 2) • 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.java
  • 27. 10.7 Polymorphism (1 of 4) • A reference variable can reference objects of classes that are derived from the variable’s class. GradedActivity exam; • We can use the exam variable to reference a GradedActivity object. • The GradedActivity class is also used as the superclass for the FinalExam class. • An object of the FinalExam class is a GradedActivity object.
  • 28. 10.7 Polymorphism (2 of 4) • A GradedActivity variable can be used to reference a FinalExam object. • This statement creates a FinalExam object and stores the object’s address in the exam variable. • This is an example of polymorphism. • The term polymorphism means the ability to take many forms. • In Java, a reference variable is polymorphic because it can reference objects of types different from its own, as long as those types are subclasses of its type.
  • 29. 10.7 Polymorphism (3 of 4) • Other legal polymorphic references: • The GradedActivity class has three methods: setScore, getScore, and getGrade. • A GradedActivity variable can be used to call only those three methods.
  • 30. Polymorphism and Dynamic Binding • If the object of the subclass has overridden a method in the superclass: – If the variable makes a call to that method the subclass’s version of the method will be run. • Java performs dynamic binding or late binding when a variable contains a polymorphic reference. • The Java Virtual Machine determines at runtime which method to call, depending on the type of object that the variable references.
  • 31. 10.7 Polymorphism (4 of 4) • It is the object’s type, rather than the reference type, that determines which method is called. • Example: – Polymorphic.java • You cannot assign a superclass object to a subclass reference variable.
  • 32. 10.8 Abstract Classes • An abstract class cannot be instantiated, but other classes are derived from it. • An Abstract class serves as a superclass for other classes. • The abstract class represents the generic or abstract form of all the classes that are derived from it. • A class becomes abstract when you place the abstract key word in the class definition.
  • 33. 10.8 Abstract Methods (1 of 2) • 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. • An abstract method has only a header and no body. • Example: – Student.java, CompSciStudent.java, CompSciStudentDemo.java
  • 34. 10.8 Abstract Methods (2 of 2) • Notice that the key word abstract appears in the header, and that the header ends with a semicolon. • 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.
  • 35. 10.9 Interfaces (1 of 3) • An interface is similar to an abstract class that has all abstract methods. – It cannot be instantiated, and – all of the methods listed in an interface must be written elsewhere. • The purpose of an interface is to specify behavior for other classes. • It is often said that an interface is like a “contract,” and when a class implements an interface it must adhere to the contract. • An interface looks similar to a class, except: – the keyword interface is used instead of the keyword class, and – the methods that are specified in an interface have no bodies, only headers that are terminated by semicolons.
  • 36. 10.9 Interfaces (2 of 3) • The general format of an interface definition: • All methods specified by an interface are public by default. • A class can implement one or more interfaces.
  • 37. 10.9 Interfaces (3 of 3) • If a class implements an interface, it uses the implements keyword in the class header. • Example: – GradedActivity.java – Relatable.java – FinalExam3.java – InterfaceDemo.java
  • 38. 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. • In this interface, FIELD1 and FIELD2 are final static int variables. • Any class that implements this interface has access to these variables.
  • 39. Implementing Multiple Interfaces • A class can be derived 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.
  • 41. Polymorphism with Interfaces (1 of 3) • 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
  • 42. Polymorphism with Interfaces (2 of 3) • 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.
  • 43. Polymorphism with Interfaces (3 of 3) • A reference to an interface can point to any class that implements that interface. • You cannot create an instance of an interface. • 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.
  • 44. Default Methods • Beginning in Java 8, interfaces may have default methods. • A default method is an interface method that has a body. • You can add new methods to an existing interface without causing errors in the classes that already implement the interface. • Example: – Displayable.java – Person.java – InterfaceDemoDefaultMethod.java
  • 45. 10.10 Anonymous Inner Classes • An inner class is a class that is defined inside another class. • An anonymous inner class is an inner class that has no name. • An anonymous inner class must implement an interface, or extend another class. • Useful when you need a class that is simple, and to be instantiated only once in your code. • Example: – IntCalculator.java – AnonymousClassDemo.java