SlideShare a Scribd company logo
UNIT-2-CHAPTER-3
INHERITANCE
Inheritance basics
 Java supports inheritance by allowing one
class to incorporate another class into its
declaration
 Done using a keyword “extend”
 Subclass adds to (extends ) the superclass
 A class that is inherited is called a superclass
 The class that does the inheriting is called
subclass
 Hence subclass is a specialized version of
superclass
 It inherits all of the variables and methods
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
 the triangle class includes all TwoDObject and
adds the field style and a method area() and
method showStyle().
 The triangle ‘s style is stored in style.
 this can be any string that describes the
triangle such as “filled” “outlined”,
“transparent”, “isosceles” or “rounded”.
 The area() method computes and returns the
area of the triangle, showStyle() displays the
triangle style.
 The general form of a class declaration that inherits a
superclass is shown here:
class subclass_name extends superclass_name{
//body of the class
}
 Can mention one superclass for any subclass that you
create.
 Java does not support the inheritance of multiple
super classes into a single subclass
 Allows to create a hierarchy of inheritance in which a
subclass becomes a super class of another subclass.
 No class is superclass of itself.
Advantage of inheritance
 Once you have created a superclass that
defines the attributes common set of objects, it
can be used to create any number of more
specific subclass
Member access and inheritance
 A subclass includes all of the members of its
superclass it cannot access those members of the
superclass that have been declared private
class TwoDshape{
private double width;
private double height;
…..
double area(){
return width*height /2;
}
}
 Program will not compile because the
reference to width and height inside the area()
method causes an access violation.
 Since width and height members are private in
nature, they are accessible only by other
members of their own class.
 Private members are not accessible outside
the class, even subclasses.
 Java uses accessor methods to provide
access to the private members of the class.
Chap3 inheritance
Chap3 inheritance
Constructors and inheritance
 The constructor for the superclass constructs
the superclass portion of the object,
constructor for the subclass constructs the
subclass part.
 The superclass has no knowledge of access to
any element in a subclass., hence their
construction must be separate.
 The superclass portion of the object is
constructed automatically using a default
constructor.
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
 Here triangle’s constructor initializes the
members of the TwoD class that it inherits
along with its own style field.
 When both the superclass and the subclass
defines as constructor, the process is more
complicated because both superclass and
subclass constructor must be executed.
Using super to call Superclass
constructors
 A subclass can call a constructor defined by its
superclass by the use of the following form of
super:
 Super(parameter_list);
 Here parameter_list specifies any parameter
needed by the constructor in the superclass
 super() must be the first statement executed
inside a subclass constructor
 Eg: defines a constructor that initializes width
and height varaible in the TwoDShape
program.
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
 Triangle() calls super() with parameters w and h.
 This causes the TwoDshape() constructor to be
called, which initialize width and height using
these values.
 Triangle no longer initializes these values itself.
 TwoDshape can add functionality about which
existing subclasses have no knowledge, thus
preventing existing code from breaking.
 Any form of constructor defined by the superclass
can be called by super()
 The constructor executed will be one that matches
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
 When a subclass calls super(), it is calling the
constructor of its immediate superclass.
 Super() always refers to the superclass
immediately above the calling class.
 It is true even in a multilevel hierarchy
 super() must always be the first statement
executed inside a constructor.
Using super to access superclass
members
 Using super we can refer to the members of
the superclass.
 General form is as follows:
 super.member
 Here the member can be either a method or
an instance variable.
 Used when the members of the subclass hide
members by the same in the superclass.
Chap3 inheritance
Chap3 inheritance
Creating a multilevel hierarchy
 Assume that there are three classes A,B and C
where C is a subclass of B, which in turn is
subclass of A.
 Here class C will inherit all of the traits found in
subclasses.
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
When are constructors called?
 Constructors are called in the order of
derivation from superclass to subclass.
 Super() must be the first statement executed in
subclass constructor.
 If super() is not used then the default
constructor will be executed.
Chap3 inheritance
Chap3 inheritance
Superclass references and
subclass objects
 Java is strongly typed language
 type compatibility is strictly enforced
 A reference variable for one class type cannot
normally refer to an object of another class type.
class X{
int a;
x(int i)
{
a= i ;
}
}
class Y{
int a;
Y(int i){
a=i;
}
}
class incompatibletypes{
X objx1=new X(10);
X objx2;
Y y=new Y(15);
objx2=x; // OK, both of same type
objx2=y; //error , not of same type
}
 Class x and y are physically same, it is not
possible to assign an X reference to Y object
they have different types.
 An object can only refer a object of its type.
 A reference variable of superclass can be
assigned a reference to an object of any
subclass derived from that superclass.
 A superclass object can refer to a subclass
object.
class X{
int a;
X (int i)
{
a=i;
}
}
class Y extends X{
int b;
Y(int i, int j){
super(j);
b= i;
}
class SupSub{
public static void main(String
args[]){
X x1=new X(10);
X x2;
Y y=new Y(5,6);
x2=x1;
System.out.println(“x2.a:”+x2.a);
x2=y;
System.out.println(“x2.a:”+x2.a);
X2.a=19; //OK
X2.b=27; //error, x does not have a
and b member
}
}
Method overriding
 When a method in a subclass has the same
return type and signature as a method in its
superclass, then the method in the subclass is
said to be override the method in superclass.
 When an overridden method is called from
within a subclass , it will always refer to the
version of that method defined by the
subclass.
 The version defined by the superclass will be
hidden.
Chap3 inheritance
 If the superclass version of an overridden
method has to be accessed then, you can do
so by using super().
 Method overriding occurs only when the
signatures of the two methods are identical.
 If they are not then, the two methods are
simply overloaded.
Chap3 inheritance
Overridden methods support
polyorphsim
 Dynamic method dispatch
 Mechanism by which call to an overridden
method is resolved at run time rather than
compile time
 Dynamic method dispatch is important
because this how java implements run-time
polymorphism.
 Is superclass reference variable can refer to a
subclass objects.
 Java determines which version of that method
to execute based upon the type of object being
referred to at a time the call occurs.
 When different types of objects are referred to,
different versions of overridden method will be
called.
 It is the type of the objects being referred to that
determines which version of an overridden
method will be executed.
 If a superclass contains a method that is
overridden by a subclass, then when different
types of objects are referred to through a
superclass reference variable , different versions
of the method are executed.
Chap3 inheritance
Chap3 inheritance
Chap3 inheritance
Why overridden methods?
 It allows to support polymorphism in JAVA
 Polymorphism allows a general class to specify
methods that will be common to all of its
derivatives, while allowing subclasses to define
the specific implementation of some or all of those
methods.
 It helps to implement “one interface, multiple
methods”
 By combining inheritance with the overridden
methods, a superclass can define the general
form of methods that will be used by all of its
subclasses.
Using Abstract Classes
 A class that determines the nature of methods
that subclasses must implement but does not
itself provide any implementation of one or
more of these methods, such a class is called
abstract class
 Defined by specifying the abstract type
modifier.
 It contains no body and is there not
implemented by the superclass
 The subclass must override it
 abstract type name(parameter_list);
 No body is present, the abstract modifier can
be used only on normal methods.
 Cannot be applied to static methods or to
constructors.
 A class that contains one or more abstract
method should be declared as abstract class
with the abstract modifier.
 Since abstract class does not define a
complete implementation, there can be no
objects of an abstract class.
 Attempting to create an object of an abstract
class, will lead to a compile time error.
 When a subclass inherits an abstract class, it
should implement all of the abstract method in
superclass
 If it does not, then the subclass must be
specified as abstract.
 Hence abstract is inherited until complete
implementation of the methods are achieved.
Chap3 inheritance
Using final
 To prevent a method from overridden, specify
that method with a keyword “final” at the start
of its declaration
 Methods declared as final cannot be
overridden
 example
Chap3 inheritance
Final prevents inheritance
 By having a class declared as final, inheritance can be
prevented
 By declaring a class as final, implicitly it declares al
the methods as final too.
 Using abstract and final together is illegal because,
abstract depends on the subclass for its
implementations and final avoids inheritance.
final class A{
//….
}
class B extends A{ //error cant have subclass of A
//….
}
Using final with data members
 final can be applied on data members of the
class.
 If we have members of class as final, the value
cannot be changed throughout the lifetime of
the program..
 Initial values can be given to the variable
 Used to create a named constant.
Chap3 inheritance
Object class
 Java defines a class called Object that is an
implicit superclass of all other classes
 All other classes are subclasses of Object
 This means that a reference variable of type
Object can refer to an object of any other
class.
 Object defines the following methods, which
are available for all objects
Method purpose
Object clone() Creates a new object that is same as the object
being cloned.
boolean equals(Object
obj)
Determines whether one object is equal to
another.
void finalize() Called before unused object to be recycled
int hashCode() Returns the hash code associated with the
invoking object
void notify() Resumes execution of a thread waiting on the
invoking object
void wait() Waits on another thread of execution
String toString() Returns a string that describes the object
Ad

More Related Content

Similar to Chap3 inheritance (20)

Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Chap11
Chap11Chap11
Chap11
Terry Yoast
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
PRN USM
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
Thakur Amit Tomer
 
Java basics
Java basicsJava basics
Java basics
Shivanshu Purwar
 
Sdtl assignment 03
Sdtl assignment 03Sdtl assignment 03
Sdtl assignment 03
Shrikant Kokate
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
M. Raihan
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
homeworkping9
 
inheritance in Java with sample program.pptx
inheritance in Java with sample program.pptxinheritance in Java with sample program.pptx
inheritance in Java with sample program.pptx
V.V.Vanniaperumal College for Women
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
HarshithaAllu
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
Nivegeetha
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
Victer Paul
 
Presentation 3.pdf
Presentation 3.pdfPresentation 3.pdf
Presentation 3.pdf
JatinGupta645530
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
teach4uin
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
PRN USM
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
M. Raihan
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
homeworkping9
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
Nivegeetha
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
Victer Paul
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
teach4uin
 

More from raksharao (20)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification & validation
Unit 7 verification & validationUnit 7 verification & validation
Unit 7 verification & validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
raksharao
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
raksharao
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
raksharao
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
raksharao
 
Unit 7 verification & validation
Unit 7 verification & validationUnit 7 verification & validation
Unit 7 verification & validation
raksharao
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
raksharao
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
raksharao
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
raksharao
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
raksharao
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
raksharao
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
raksharao
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
raksharao
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
raksharao
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
raksharao
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
raksharao
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
raksharao
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
raksharao
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Ad

Recently uploaded (20)

Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Ad

Chap3 inheritance

  • 2. Inheritance basics  Java supports inheritance by allowing one class to incorporate another class into its declaration  Done using a keyword “extend”  Subclass adds to (extends ) the superclass  A class that is inherited is called a superclass  The class that does the inheriting is called subclass  Hence subclass is a specialized version of superclass  It inherits all of the variables and methods
  • 6.  the triangle class includes all TwoDObject and adds the field style and a method area() and method showStyle().  The triangle ‘s style is stored in style.  this can be any string that describes the triangle such as “filled” “outlined”, “transparent”, “isosceles” or “rounded”.  The area() method computes and returns the area of the triangle, showStyle() displays the triangle style.
  • 7.  The general form of a class declaration that inherits a superclass is shown here: class subclass_name extends superclass_name{ //body of the class }  Can mention one superclass for any subclass that you create.  Java does not support the inheritance of multiple super classes into a single subclass  Allows to create a hierarchy of inheritance in which a subclass becomes a super class of another subclass.  No class is superclass of itself.
  • 8. Advantage of inheritance  Once you have created a superclass that defines the attributes common set of objects, it can be used to create any number of more specific subclass
  • 9. Member access and inheritance  A subclass includes all of the members of its superclass it cannot access those members of the superclass that have been declared private class TwoDshape{ private double width; private double height; ….. double area(){ return width*height /2; } }
  • 10.  Program will not compile because the reference to width and height inside the area() method causes an access violation.  Since width and height members are private in nature, they are accessible only by other members of their own class.  Private members are not accessible outside the class, even subclasses.  Java uses accessor methods to provide access to the private members of the class.
  • 13. Constructors and inheritance  The constructor for the superclass constructs the superclass portion of the object, constructor for the subclass constructs the subclass part.  The superclass has no knowledge of access to any element in a subclass., hence their construction must be separate.  The superclass portion of the object is constructed automatically using a default constructor.
  • 18.  Here triangle’s constructor initializes the members of the TwoD class that it inherits along with its own style field.  When both the superclass and the subclass defines as constructor, the process is more complicated because both superclass and subclass constructor must be executed.
  • 19. Using super to call Superclass constructors  A subclass can call a constructor defined by its superclass by the use of the following form of super:  Super(parameter_list);  Here parameter_list specifies any parameter needed by the constructor in the superclass  super() must be the first statement executed inside a subclass constructor  Eg: defines a constructor that initializes width and height varaible in the TwoDShape program.
  • 23.  Triangle() calls super() with parameters w and h.  This causes the TwoDshape() constructor to be called, which initialize width and height using these values.  Triangle no longer initializes these values itself.  TwoDshape can add functionality about which existing subclasses have no knowledge, thus preventing existing code from breaking.  Any form of constructor defined by the superclass can be called by super()  The constructor executed will be one that matches
  • 28.  When a subclass calls super(), it is calling the constructor of its immediate superclass.  Super() always refers to the superclass immediately above the calling class.  It is true even in a multilevel hierarchy  super() must always be the first statement executed inside a constructor.
  • 29. Using super to access superclass members  Using super we can refer to the members of the superclass.  General form is as follows:  super.member  Here the member can be either a method or an instance variable.  Used when the members of the subclass hide members by the same in the superclass.
  • 32. Creating a multilevel hierarchy  Assume that there are three classes A,B and C where C is a subclass of B, which in turn is subclass of A.  Here class C will inherit all of the traits found in subclasses.
  • 36. When are constructors called?  Constructors are called in the order of derivation from superclass to subclass.  Super() must be the first statement executed in subclass constructor.  If super() is not used then the default constructor will be executed.
  • 39. Superclass references and subclass objects  Java is strongly typed language  type compatibility is strictly enforced  A reference variable for one class type cannot normally refer to an object of another class type. class X{ int a; x(int i) { a= i ; } }
  • 40. class Y{ int a; Y(int i){ a=i; } } class incompatibletypes{ X objx1=new X(10); X objx2; Y y=new Y(15); objx2=x; // OK, both of same type objx2=y; //error , not of same type }
  • 41.  Class x and y are physically same, it is not possible to assign an X reference to Y object they have different types.  An object can only refer a object of its type.  A reference variable of superclass can be assigned a reference to an object of any subclass derived from that superclass.  A superclass object can refer to a subclass object.
  • 42. class X{ int a; X (int i) { a=i; } } class Y extends X{ int b; Y(int i, int j){ super(j); b= i; } class SupSub{ public static void main(String args[]){ X x1=new X(10); X x2; Y y=new Y(5,6); x2=x1; System.out.println(“x2.a:”+x2.a); x2=y; System.out.println(“x2.a:”+x2.a); X2.a=19; //OK X2.b=27; //error, x does not have a and b member } }
  • 43. Method overriding  When a method in a subclass has the same return type and signature as a method in its superclass, then the method in the subclass is said to be override the method in superclass.  When an overridden method is called from within a subclass , it will always refer to the version of that method defined by the subclass.  The version defined by the superclass will be hidden.
  • 45.  If the superclass version of an overridden method has to be accessed then, you can do so by using super().  Method overriding occurs only when the signatures of the two methods are identical.  If they are not then, the two methods are simply overloaded.
  • 47. Overridden methods support polyorphsim  Dynamic method dispatch  Mechanism by which call to an overridden method is resolved at run time rather than compile time  Dynamic method dispatch is important because this how java implements run-time polymorphism.  Is superclass reference variable can refer to a subclass objects.  Java determines which version of that method to execute based upon the type of object being referred to at a time the call occurs.
  • 48.  When different types of objects are referred to, different versions of overridden method will be called.  It is the type of the objects being referred to that determines which version of an overridden method will be executed.  If a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable , different versions of the method are executed.
  • 52. Why overridden methods?  It allows to support polymorphism in JAVA  Polymorphism allows a general class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.  It helps to implement “one interface, multiple methods”  By combining inheritance with the overridden methods, a superclass can define the general form of methods that will be used by all of its subclasses.
  • 53. Using Abstract Classes  A class that determines the nature of methods that subclasses must implement but does not itself provide any implementation of one or more of these methods, such a class is called abstract class  Defined by specifying the abstract type modifier.  It contains no body and is there not implemented by the superclass  The subclass must override it  abstract type name(parameter_list);
  • 54.  No body is present, the abstract modifier can be used only on normal methods.  Cannot be applied to static methods or to constructors.  A class that contains one or more abstract method should be declared as abstract class with the abstract modifier.  Since abstract class does not define a complete implementation, there can be no objects of an abstract class.
  • 55.  Attempting to create an object of an abstract class, will lead to a compile time error.  When a subclass inherits an abstract class, it should implement all of the abstract method in superclass  If it does not, then the subclass must be specified as abstract.  Hence abstract is inherited until complete implementation of the methods are achieved.
  • 57. Using final  To prevent a method from overridden, specify that method with a keyword “final” at the start of its declaration  Methods declared as final cannot be overridden  example
  • 59. Final prevents inheritance  By having a class declared as final, inheritance can be prevented  By declaring a class as final, implicitly it declares al the methods as final too.  Using abstract and final together is illegal because, abstract depends on the subclass for its implementations and final avoids inheritance. final class A{ //…. } class B extends A{ //error cant have subclass of A //…. }
  • 60. Using final with data members  final can be applied on data members of the class.  If we have members of class as final, the value cannot be changed throughout the lifetime of the program..  Initial values can be given to the variable  Used to create a named constant.
  • 62. Object class  Java defines a class called Object that is an implicit superclass of all other classes  All other classes are subclasses of Object  This means that a reference variable of type Object can refer to an object of any other class.  Object defines the following methods, which are available for all objects
  • 63. Method purpose Object clone() Creates a new object that is same as the object being cloned. boolean equals(Object obj) Determines whether one object is equal to another. void finalize() Called before unused object to be recycled int hashCode() Returns the hash code associated with the invoking object void notify() Resumes execution of a thread waiting on the invoking object void wait() Waits on another thread of execution String toString() Returns a string that describes the object
  翻译: