Upload
jason-ruiz
View
239
Download
0
Embed Size (px)
Citation preview
8/12/2019 Chapter 1 Overview of OOP
1/154
8/12/2019 Chapter 1 Overview of OOP
2/154
Chapter Topics
0 OOP
0 Classes and Objects
0 Encapsulation0 Abstraction
0 Inheritance
0 Polymorphism
0 Abstract class & interfaces
0 Exceptions & Review of Java Fundamentals
Chapter 1 - OOP Principles 2
8/12/2019 Chapter 1 Overview of OOP
3/154
Object Oriented Programming0 Object orientationis a set of tools and methods that enable
software engineers to build reliable, user friendly, maintainable,
well documented, reusable software systems that fulfills the
requirements of its users.
0 Object-orientation provides a new view of computation.
0 A software system is seen as a community of objects that cooperate
with each other by passing messages in solving a problem.
0 At the heart of object-oriented programming, instead of tasks we
find objects entities that:
0 have behaviors,
0 hold information, and
0 can interact with one another.
Chapter 1 - OOP Principles
3
8/12/2019 Chapter 1 Overview of OOP
4/154
Object Oriented Programming0 An object-oriented programming language provides support for
the following object-oriented concepts:
0 Objects
0 Classes
0 Inheritance
0 Polymorphism
0 Abstraction
0 Modularity
0 Encapsulation
Chapter 1 - OOP Principles
4
8/12/2019 Chapter 1 Overview of OOP
5/154
Object Oriented ProgrammingBenefits of OOP
0 The concept of inheritance and the data-oriented approach allow a lot ofreuse of existing classes and helps to eliminate redundant code.
0 Programs can be built using working modules that already know how tocommunicate with each other. This means that programs do not always haveto be written from scratch thus saving development time and increasingproductivity.
0 Encapsulation (hiding of data) helps with the building of more secureprograms as data cannot be unintentionally changed by other parts of theprogram.
0 There is a close link between objects in the real-world system and objects inthe program. Therefore the structure of the system is more likely to bemeaningful to users.
0 The work for a project can be divided by class/object making it easier tosplit work up between a team of developers.
0 OO systems can be easily upgraded from small to larger systems.
0 The message passing technique for communication between objects makes iteasy to describe the interface of an OO system for other systems that need tocommunicate with it.
0 Software complexity can be easily managed.
Chapter 1 - OOP Principles
5
8/12/2019 Chapter 1 Overview of OOP
6/154
Class0 Definition: A class is a blueprint that defines the variables and the
methods common to all objects of a certain kind.
0 A class is a software blueprint for objects. A class is used to
manufacture or create objects.
0 The class declares the instance variables necessary to contain the state
of every object.
0 The class would also declare and provide implementations for theinstance methods necessary to operate on the state of the object.
0 After youve created the class, you can create any number of objects
from that class.
0 Parts of the class specify, or describe, what variables and methods theobjects will contain.
0 Objects are created and destroyed as the program runs, and there can
be many objects with the same structure, if they are created using the
same class.
Chapter 1 - OOP Principles
6
8/12/2019 Chapter 1 Overview of OOP
7/154
Class0 Declaring a Class
classclassname {
datatype instance-variable1;datatype instance-variable2;// ...
datatype instance-variableN;
returntype methodname1(parameter-list) {
// body of method
}returntype methodname2(parameter-list) {
// body of method
}
// ...
returntype methodnameN(parameter-list) {// body of method
}
}
0 You can also add modifiers likepublicorprivateat the very beginning.
Chapter 1 - OOP Principles
7
8/12/2019 Chapter 1 Overview of OOP
8/154
Class0 In general, class declarations can include these components, in
order:
0 Modifierssuch aspublic,private,protected,
0 The classname,
0 with the initial letter capitalized by convention.
0 The name of the class's parent (superclass), if any,
0 preceded by the keyword extends. A class can only extend(subclass) one
parent.
0 A comma-separated list of interfaces implemented by the class, if
any,
0 preceded by the keyword implements. A class can implementmore thanone interface.
0 The class body, surrounded by braces, {}.
Chapter 1 - OOP Principles
8
8/12/2019 Chapter 1 Overview of OOP
9/154
Class
Variables or Methods withthis modifier can be
acessed by methods in:
variable or method modifier
Public Private Protected No modifier (default)same class Y Y Y Y
Classes in same package Y N Y YSubclasses Y N Y N
Classes in different
packages Y N N NChapter 1 - OOP Principles
9
Access Protection
8/12/2019 Chapter 1 Overview of OOP
10/154
8/12/2019 Chapter 1 Overview of OOP
11/154
8/12/2019 Chapter 1 Overview of OOP
12/154
cont0 Line 1: is multiple line comment which is like in C++.
/*multiple line comment*/
0 Line 2: class Example {
0 This line uses the keyword class to declare that a new class is
being defined.
0 Example is an identifier that is the name of the class. The entireclass definition, including all of its members, will be between the
opening curly brace ({) and the closing curly brace (}).
0 The use of the curly braces in Java is identical to the way they are
used in C, C++, and C#.
0 Line 3: is the single-line comment which is like in C++.
// single line comment
Chapter 1 - OOP Principles 12
8/12/2019 Chapter 1 Overview of OOP
13/154
cont0 Line 4:public static void main(String args[]) {
0 This line begins the main( ) method. As the comment preceding it
suggests, this is the line at which the program will begin executing.
All Java applications begin execution by calling main( ). (This is
just like C/C++.)
0 The public keyword is an access specifier, which allows the
programmer to control the visibility of class members. When a
class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared. (The
opposite of public is private, which prevents a member from
being used by code defined outside of its class.)0 In this case, main( ) must be declared as public, since it must be
calledby code outside of its class when the program is started.
Chapter 1 - OOP Principles 13
8/12/2019 Chapter 1 Overview of OOP
14/154
cont0 The keyword static allows main( ) to be called without having to
instantiate a particular instance of the class. This is necessary since
main( ) is called by the Java interpreter before any objects are
made.
0 The keyword void simply tells the compiler that main() does not
return a value.
0 In main( ), there is only one parameter, albeit a complicated one.
String args[ ] declares a parameter namedargs, which is an array
of instances of the class String. (Arrays are collections of similar
objects.) Objects of type String store character strings.
0 In this case, args receives anycommand-line argumentspresentwhen the program is executed.
Chapter 1 - OOP Principles 14
8/12/2019 Chapter 1 Overview of OOP
15/154
cont0 Line:5
System.out.println(Hello Comps!");
0 This line outputs the string Hello Comps! followed by a new lineon the screen.
0 Output is actually accomplished by the built-in println() method.
In this case, println( ) displays the string which is passed to it.
0 As you will see, println( ) canbe used to display other types of
information, too.
0 The line begins with System.out. - System is a predefined class
that provides access to the system, and out is the output stream
that is connected to the console
Chapter 1 - OOP Principles 15
8/12/2019 Chapter 1 Overview of OOP
16/154
6.Structure of a Class0 All Java code is written inside classes.
0 The class definition is the first part of the code that appears. This
consists of the access modifier for the class (public or private), the
class keyword and the name of the class.
0 By convention, class names begin with an upper case letter.For
example, to define a class called Circle :
public class Circle
{
}
Chapter 1 - OOP Principles 16
8/12/2019 Chapter 1 Overview of OOP
17/154
cont0 Inside the class, the code can be divided into fields, constructors
and methods.
0 The fieldsare the data members of the class. The data members
can be class variables or instance variables.
0 The constructorsare special methods that are called when an
object is instantiated from the class. There can be more than one
constructor for a class as long as each constructor has a different
parameter list. For example, in a Circle class, the radius for a new
object could be passed to the constructor, or if no radius is passed,
a default value could be assigned for the radius. In fact, this also
applies to methods. This feature of Java is called methodoverloading.
Chapter 1 - OOP Principles 17
8/12/2019 Chapter 1 Overview of OOP
18/154
cont0 The methodsimplement the behaviour of the objects belonging to
the class. Generally, methods return information about the state of
an object or they change the state of an object. These aresometimes called accessorand mutatormethods.
0 The order of these parts of a class is generally not important, but
placing the fields and then the constructors at the beginning does
make the class readable and easy to get around for programmers.Of course, comment blocks should also be used to document the
code.
Chapter 1 - OOP Principles 18
8/12/2019 Chapter 1 Overview of OOP
19/154
cont (Eg)public class Circle{
//data
private double radius;
//constructors
public void Circle ()
{ radius = 1.0;}
public void Circle (double r)
{ radius = r; }
//methods
public double calcArea()
{
return 3.14* radius * radius;
}
public void draw()
{
}
}Chapter 1 - OOP Principles 19
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
20/154
Defining Methods0 To declare method:
modifier returntypenameOfMethod(parrameterlist) {
//body of the method
}
0 The only required elements of a method declaration are themethod's return type, name, a pair of parentheses, ( ), and a body
between braces, {}.
0 Note:Parametersrefers to the list of variables in a method
declaration.0 Argumentsare the actual values that are passed in when the
method is invoked. When you invoke a method, the arguments
used must match the declaration's parameters in type and order.Chapter 1 - OOP Principles 20
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
21/154
Defining Methods(cont)0 More generally, method declarations have six components, in
order:
0 Modifierssuch as public, private, and others.
0 The return typethe data type of the value returned by the method,or void if the method does not return a value.
0 The method name
0 The parameter list in parenthesisa comma-delimited list of inputparameters, preceded by their data types, enclosed by parentheses, ().
0If there are no parameters, you must use emptyparentheses.
0 An exception list
0 The method body, enclosed between braces
0 Definition:Two of the components of a method declarationcomprise the method signaturethe method'snameand theparameter types.
Chapter 1 - OOP Principles 21
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
22/154
Defining Methods(cont)
Naming a Method0 Although a method name can be any legal identifier, codeconventions restrict method names.
0 By convention, method names should be a verbin
lowercaseor a multi-wordname that begins with a verb in
lowercase, followed by adjectives, nouns, etc.
0 In multi-word names, the first letter of each of the second and
following words should be capitalized.
Chapter 1 - OOP Principles 22
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
23/154
Defining Methods(cont)
Overloading Methods0 Overloading is when the same method or operator can beused on many different types of data.
0 The Java programming language supports overloading
methods, and Java can distinguish between methods withdifferent method signatures.
0 This means that methods within a class can have the same
name if they have different parameter lists
0 Java does not support operator overloading.
Chapter 1 - OOP Principles 23
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
24/154
Defining Methods(cont)
Overloading Methods(cont)0 Overloaded methods are differentiated by the number
and the type of the arguments passed into the
method.
0 You cannot declare more than one method with the
same name and the same number and type of
arguments
0 fThe compiler does not consider return type when
differentiating methods, so you cannot declare two
methods with the same signature even if they have a
different return type.
Chapter 1 - OOP Principles 24
Defining Methods(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
25/154
Defining Methods(cont)
Overloading Methods(cont)0 Example on Overloading methods
classRectangle {
float height, width;float calculateArea(float h, float w) {
return (h*w);
}
float calculateArea(int h, float w){
return (h*w);
}float calculateArea(float h, int w){
return (h*w);
}
int calculateArea(int h, int w){
return (h*w);
}int calculateArea(int h){
return (h*h);
}
int calculateArea(){
return (0);
}Chapter 1 - OOP Principles 25
b
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
26/154
Objects0 Definition: An object is a software bundle of variables and
related methods.
0 In OOP we create software objects that model real world objects.
0 Software objects are modeled after real-world objects in that
they have state and behavior.
0 A software object maintains its state in one or more variables. A
variable is an item of data named by an identifier.
0 A software object implements its behavior with methods. A method
is a function associated with an object.
0 An object is also known as an instance. An instance refers to a
particular object.
0 The variables of an object are formally known as instance
variables because they contain the state for a particular object or
instance.
Chapter 1 - OOP Principles
26
b
8/12/2019 Chapter 1 Overview of OOP
27/154
Objects0 An object
stores its stateinfields(variables in some programming languages) and
exposes behaviorthrough methods(functions in some programminglanguages).
0 Bundling code into individual software objects provides a number of
benefits, including:
0 Modularity: The source code for an object can be written and maintained
independently of the source code for other objects.
0 Information-hiding: By interacting only with an object's methods, the
details of its internal implementation remain hidden from the outside
world.
0 Codere-use: If an object already exists you can use that object in your
program. This allows specialists to implement/test/debug complex, task-
specific objects.
0 Pluggabilityand debuggingease: If a particular object turns out to be
problematic, you can simply remove it from your application and plug in a
different object as its replacement.Chapter 1 - OOP Principles
27
8/12/2019 Chapter 1 Overview of OOP
28/154
Question:
If an object is also a collection of variables and methods,how do they differ from classes?
Answer:
No memory is allocated when a class is created. Memory allocationhappens only when the actual instances of a class(the objects) are
created.
Chapter 1 - OOP Principles 28
8/12/2019 Chapter 1 Overview of OOP
29/154
Creating Objects
0 A class provides the blueprint for objects; you create an objectfrom a class.
0 Creating objects has three part:
0 Declaration: associate a variable name with an object type.
0 Instantiation: The new keyword is a Java operator that creates theobject.
0 Initialization: The new operator is followed by a call to a constructor,
which initializes the new object.
Chapter 1 - OOP Principles 29
8/12/2019 Chapter 1 Overview of OOP
30/154
Creating Objects(cont)1.Declaration
0 Declaring a Variable to Refer to an Objecttype name;
0 This notifies the compiler that you will use nameto refer to data
whose type is type.
0 With a primitive variable, this declaration also reserves the properamount of memory for the variable.
0 Simply declaring a reference variable does not create an
object. For that, you need to use the newoperator.
0 A variable in this state, which currently references no
object
e.g., RectangleRec1;Chapter 1 - OOP Principles 30
C ti Obj t ( t)
8/12/2019 Chapter 1 Overview of OOP
31/154
Creating Objects(cont)2. Instantiating a Class
0 The newoperator instantiates a class by allocating memory for a
new object and returning a reference to that memory.
0 The newoperator also invokes the object constructor.
0 The newoperator requires a single, postfix argument: a call to a
constructor.
0 The name of the constructor provides the name of the class to
instantiate.
0 Reference is usually assigned to a variable of the appropriate type,
like:
Rectangle Rec1; //declaration
Rec1= newRectangle (); Intantiation
Chapter 1 - OOP Principles 31
C ti Obj t ( t)
8/12/2019 Chapter 1 Overview of OOP
32/154
Creating Objects(cont)2. Instantiating a Class(cont)
0 Eg. Line 1 : Rectangle Rec1;
Line 2 : Rectangle Rec1= new Rectangle ();
0 The first line declares Rec1 as a reference to an object of type
Rectangle . After this line executes, Rec1 contains the value null,
which indicates that itdoes not yet point to an actual object. Any
attempt to use Rec1 at this point willresult in acompile-time
error.
0 The second line allocatesan actual object and assigns a reference
to it to Rec1 . After the second line executes, you can use Rec1 as if
it were a Rectangle object. But in reality, Rec1 simply holdsthememory address of the actual Rectangle object.
Chapter 1 - OOP Principles 32
Creating Objects(cont)
8/12/2019 Chapter 1 Overview of OOP
33/154
Creating Objects(cont)
3. Initializing an Object0 Here's the code for the Rectangle class:
classRectangle {
float height = 1, width =1;
float calculateArea(float h, float w) {
return (h*w);
}// constructor
public Rectangle(float h, float w){
height = h;
width = w;
} }
0 The following statement provides 2 and 4 as values for those arguments:
Rectangle Rec1= newRectangle (2,4); // this will initialize themembers of Rec1, i.e Rec1.height to be 2 and Rec1.width to 4.
Chapter 1 - OOP Principles 33
8/12/2019 Chapter 1 Overview of OOP
34/154
Referencing an Object's Fields
0 Object fields are accessed by their name. You must
use a name that is unambiguous.
0 You may use a simple name for a field within its own
class.
0 Code that is outsidethe object's class must use an
object reference or expression, as in:
objectReference.fieldName;
0 Objects of the same type have their own copy of the
same instance fields.
Chapter 1 - OOP Principles 34
8/12/2019 Chapter 1 Overview of OOP
35/154
Object referencing
0 When you access an instance field through an object
reference, you are referencing the particular object's
field.
0 To access a field, you can use a named reference to an
object, or you can use any expression that returns an
object reference.
0 Recall that the newoperator returns a reference to an
object.
int height = newRectangle().height;
Chapter 1 - OOP Principles 35
8/12/2019 Chapter 1 Overview of OOP
36/154
Calling an Object's Methods
0 Once you've created an object, you probably want to use it for
something.
0 You may need to use the value of one of its fields, change one of its
fields, or call one of its methods to perform an action.
0 You also use an object reference to invoke an object's method.
0 You appendthe method's simple name to the object reference,
with an intervening dotoperator (.). Also, you provide, within
enclosing parentheses, any arguments to the method. If the method
does not require any arguments, use empty parentheses.
objectReference.methodName(argumentList);
orobjectReference.methodName();
Chapter 1 - OOP Principles 36
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
37/154
Constructors
0 A constructor createsa new instance of the class.
0 It initializesall the variables and does any worknecessary to prepare the class to be used.
0 A constructor has the same name as the class.
0 If no constructor exists Java provides a generic onethat takes no arguments which is called the defaultconstructor.
0 You make a constructor by writing a method that
has the same name as the class.
Chapter 1 - OOP Principles 37
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
38/154
Constructors(cont)0 Constructors do not have return types.
0 They do returnan instanceof their own class, but this is
implicit(hidden), not explicit.0 Example:
// constructors
Rectangle(){ // editing the default constructor
height = 1;width = 1;
}
Rectangle(float height, float width){ // parametrized
constructorthis.height = height;
this.width = width;
} Chapter 1 - OOP Principles 38
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
39/154
Constructors(cont)0 Example:classRectangle {
float height;
float width;
float calculateArea(float h, float w) {
return (h*w);
}
// constructors
Rectangle(){ // editing the default constructor
height = 1;
width = 1;
}Rectangle(float height, float width){ // parametrized constructor
this.height = height;
this.width = width;
}
}Chapter 1 - OOP Principles 39
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
40/154
Constructors(cont)0In the above eg, weve used a keyword this
Rectangle(float height, float width){ // parametrizedconstructor
this.height = height;
this.width = width;
}0 Sometimes a method will need to refer to the object that
invoked it. To allow this, Java defines the this keyword.
0 this can be used inside any method to refer to the current
object.0 That is, this is always areference to the object on which the
method was invoked. You can use this anywhere a reference toan object of the current class type is permitted.
Chapter 1 - OOP Principles 40
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
41/154
Constructors(cont)
Parameter Types0 You can use any data type for a parameter of a method or a
constructor.
0 This includes primitive data types, such as doubles, floats, and
integers, and reference data types, such as objects and arrays. Eg:
Eg.1: public Polygon polygonFrom(Rectangle[] recs) {
// method body goes here}
Eg.2: public int Something(int[] x) { //
// method body goes here
}
0 Note:The Java programming language doesn't let you
pass methods into methods. But you can pass an object
into a method and then invoke the object's methods.Chapter 1 - OOP Principles 41
C ( )
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
42/154
Constructors(cont)
Arbitrary Number of Arguments
0 You can use a construct called varargsto pass an
arbitrary number of values to a method.
0 To use varargs, you follow the type of the last
parameter by an ellipsis(three dots, ...), then a space,
and the parameter name.
0 The method can then be called with any number of
that parameter, including none.
0 The method can be called either with an array or with a
sequence of arguments. The code in the method body
will treat the parameter as an array in either case.
Chapter 1 - OOP Principles 42
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
43/154
Constructors(cont)
Arbitrary Number of
Arguments(cont)public int calculateArea(Rectangle... recs) {
recs[0].height = 4;
recs[0].width = 5;return (calculate(recs[0].calculateArea(1,2)));
}
Let say we have an object called Rec1,
And you can call this method like this:
int result = Rec1.calculateArea(Rec1);
Chapter 1 - OOP Principles 43
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
44/154
Constructors(cont)
Parameter Names0 The name of a parameter must be unique in its scope.
0 It cannot be the same as the name of another parameter for the same
method or constructor, and it cannot be the name of a local variable
within the method or constructor.
0 A parameter can have the same name as one of the class's fields.
0 If this is the case, the parameter is said toshadowthe field.0 For example, consider the following Circle class and its setOrigin
method:
public class Circle {
private int x, y, radius;public void setOrigin(int x, int y) {
...
}
}
Chapter 1 - OOP Principles 44
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
45/154
Constructors(cont)Passing Primitive Data Type
Arguments0 Primitive arguments, such as an int or a double, are
passed into methods by value.
0 This means that any changes to the values of the
parameters exist only within the scope of the method.
0 When the method returns, the parameters are gone and
any changes to them are lost.
Chapter 1 - OOP Principles 45
Constructors(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
46/154
Constructors(cont)Passing Reference Data Type
Arguments0 Reference data type parameters, such as objects, are
also passed into methods by value.
0 This means that when the method returns, the passed-in
reference still references the same object as before.
0 However, the values of the object's fields canbe changed
in the method, if they have the proper access level.
Chapter 1 - OOP Principles 46
Example:class Rectangle {
class MethodsAndConstructors{bli t ti id i (St i [] ){
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
47/154
Chapter 1 - OOP Principles 47
g
float height;
float width;
float calculateArea() {
return (height*width);
}
public changeValue(Rectangle[] rec){
rec[0].height = 2;
rec[0].width = 2;
}
public changeValueByVar(Rectangle recs){
recs[0].height = 4;
rec[s0].width = 4;
}
// constructors
Rectangle(){ // editing the default constructor
height = 1;
width = 1;
}
Rectangle(float height, float width){ //
parametrized constructorthis.height = height;
this.width = width;
}
}
public static void main(String[] args){
Rectangle R1=new Rectangle();
System.out.println(R1-height+R1. height +R1-width + R1.widht);
System.out.println(R1-Area+R1.calculateArea());
R1.changeValue(R1) ;
System.out.println(R1-height+R1. height +R1-width + R1.widht);
System.out.println(R1-Area+R1.calculateArea());
Rectangle R2=new Rectangle(5,3);
System.out.println(R2-height+R2. height +R2-width + R2.widht);
System.out.println(R2-Area+R2.calculateArea());
R2.changeValueByVar(R1) ;
System.out.println(R1-height+R1. height +R1-width + R1.widht);
System.out.println(R1-Area+R1.calculateArea());
}
}
8/12/2019 Chapter 1 Overview of OOP
48/154
Using the this keyword(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
49/154
Using the this keyword(cont)0 but it could have been written like this:
0 public class Point {
public int x = 0; public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x; this.y = y;}
}
0 Each argument to the constructor shadows one of the object's
fields inside the constructor xis a local copy of the constructor'sfirst argument. To refer to the Point field x, the constructor must
use this.x.
Chapter 1 - OOP Principles 49
Using the this keyword(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
50/154
Using the this keyword(cont)Using this with a Constructor
0 From within a constructor, you can also use the thiskeyword to call another
constructor in the same class. Doing so is called an explicit constructor
invocation.
public class Rectangle {
private int x, y; private int width, height;
public Rectangle() {
this(0, 0, 0, 0);}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x; this.y = y; this.width = width; this.height = height;
}
...
}
Chapter 1 - OOP Principles 50
Using the this keyword(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
51/154
Using the this keyword(cont)
0 This class contains a set of constructors. Each constructor
initializes some or all of the rectangle's member variables.0 The constructors provide a default value for any member variable
whose initial value is not provided by an argument.
0 For example, the no-argument constructor calls the four-argument
constructor with four 0 values and the two-argument constructorcalls the four-argument constructor with two 0 values.
0 As before, the compiler determines which constructor to call,
based on the number and the type of arguments.
0 If present, the invocation of another constructor must be the firstline in the constructor.
Chapter 1 - OOP Principles 51
Encapsulation
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
52/154
Encapsulation Encapsulationis the hidingof dataimplementation by
restricting access to accessors and mutators.
Encapsulation is the technique of making thefieldsin a class
private and providing access to the fields viapublic methods. If
a field is declared private, it cannot be accessed by anyone
outside the class, thereby hiding the fields within the class. For
this reason, encapsulation is also referred to as data hiding. Accessor : is a method that is used to ask an object about
itself. Accessor methods are any public method that gives
information about the state of the object.
Mutator: are public methods that are used to modify thestate of an object, while hiding the implementation of exactly
how the data gets modified.
Chapter 1 - OOP Principles
52
Encapsulation
8/12/2019 Chapter 1 Overview of OOP
53/154
EncapsulationClass Person{
private String fullName;
public String setFullName(String _fullName){fullName = _fullName;
}
public String getFullName(){
return fullName;}
}
So, the use of mutators and accessors provides many advantages. Byhiding the implementation of our Person class, we can make
changes to the Person class without the worry that we are going tobreak other code that is using and calling the Person class forinformation.
This type of dataprotectionand implementationprotectioniscalled Encapsulation.
Chapter 1 - OOP Principles
53
The Garbage Collector
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
54/154
The Garbage Collector
0 Some object-oriented languages require that you keep track of all the
objects you create and that you explicitly destroy them when they areno longer needed.
0 Managing memory explicitly is tedious and error-prone.
0 The Java platform allows you to create as many objects as you want
(limited, of course, by what your system can handle), and you don'thave to worry about destroying them.
0 The Java runtime environment deletesobjectswhen it
determinesthat they are no longer being used. This process is
calledgarbage collection.
Chapter 1 - OOP Principles 54
The Garbage Collector(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
55/154
The Garbage Collector(cont)0 An object is eligible for garbage collection when there are no
more references to that object.
0 References that are held in a variable are usually dropped when
the variable goes out of scope. Or, you can explicitly drop an
object reference by setting the variable to the special value null.
0 Remember that a program can have multiple references to the
same object; all references to an object must be dropped before
the object is eligible for garbage collection.
0 The Java runtime environment has a garbage collector that
periodically frees the memory used by objects that are no longer
referenced. The garbage collector does its job automatically when
it determines that the time is right.
Chapter 1 - OOP Principles 55
Nested Classes
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
56/154
Nested Classes0 The Java programming language allows you to define a class
within another class. Such a class is called a nested classand is
illustrated here:classOuterClass {
...
classNestedClass {
...}
}
0 Nested classes are divided into two categories: staticand non-
static.0 Nested classes that are declared static are simply calledstatic
nested classes.
0 Non-static nested classes are called inner classes.Chapter 1 - OOP Principles 56
Nested Classes(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
57/154
Nested Classes(cont)class OuterClass {
...
static class StaticNestedClass {...
}
class InnerClass {
...
}}
0 A nested class is a member of its enclosing class.
0 Non-staticnested classes (inner classes) have accessto othermembers of the enclosing class, even if they are declared private.
0 Static nested classes do not have access to other members ofthe enclosing class.
0 As a member of the OuterClass,a nested class can be declaredprivate, public, protected, orpackage private.
Chapter 1 - OOP Principles 57
N t d Cl ( t)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
58/154
Nested Classes(cont)
Static Nested Classes0 A static nested class is associated with its outer class.
0 And like static class methods, a static nested class cannot refer
directlyto instance variables or methods defined in its enclosing
class it can use them only through an object reference.
0 Note:A static nested class interacts with the instance members of
its outer class (and other classes) just like any other top-level
class. In effect, a static nested class is behaviorally a top-level
class that has been nested in another top-level class for packaging
convenience.
Chapter 1 - OOP Principles 58
Nested Classes(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
59/154
Nested Classes(cont)
Static Nested Classes(cont)0 Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
0 For example, to create an object for the static nested class, use this
syntax:
OuterClass.StaticNestedClass nestedObject= new
OuterClass.StaticNestedClass();
Chapter 1 - OOP Principles 59
Nested Classes(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
60/154
Nested Classes(cont)
Inner Classes0 As with instance methods and variables, an inner class is
associated with an instance of its enclosing class and has direct
accessto that object's methods and fields.
0 Also, because an inner class is associated with an instance, it
cannot define any static members itself.
0 Objects that are instances of an inner class exist withinan
instance of the outer class. Consider the following classes:
class OuterClass {
...
class InnerClass { ... }
} Chapter 1 - OOP Principles 60
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
61/154
http://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
62/154
Nested Classes(cont)
Inner Classes(cont)
Local and Anonymous Inner Classes0 There are two additional types of inner classes.
0 You can declarean inner class withinthe bodyof a method. Such a
class is known as a local inner class.
0 You can also declare an inner class withinthe bodyof a methodwithoutnamingit. These classes are known as anonymous inner
classes.
0 You will encounter such classes in advanced Java programming.
Chapter 1 - OOP Principles 62
Nested Classes(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
63/154
( )Types of nested classes
Types of Nested Classes
Type Scope Innerstatic nested class member noinner [non-static]
class member yeslocal class local yes
anonymous class only the pointwhere it is defined yes
Chapter 1 - OOP Principles 63
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
64/154
Nested Classes(cont)
Why Use Nested Classes?0 There are several compelling reasons for using nested
classes, among them:
0 It is a way of logically grouping classes that are only
used in one place.
0 It increases encapsulation.
0 Nested classes can lead to more readable and
maintainable code.
Chapter 1 - OOP Principles 64
Nested Classes(cont)
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
65/154
Nested Classes(cont)
Why Use Nested Classes?(cont)
0 Logical grouping of classesIf a class is useful to only one otherclass, then it is logical to embed it in that class and keep the two
together. Nesting such "helper classes" makes their package more
streamlined.
0 Increased encapsulationConsider two top-level classes, A and B,
where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members can
be declared private and B can access them. In addition, B itself can
be hidden from the outside world.
0 More readable, maintainable codeNesting small classes withintop-level classes places the code closer to where it is used.
Chapter 1 - OOP Principles 65
http://docs.oracle.com/javase/tutorial/java/concepts/object.htmlhttp://docs.oracle.com/javase/tutorial/java/concepts/object.html8/12/2019 Chapter 1 Overview of OOP
66/154
The 4 basic Principles of OOP at a Glance
0 The 4 major principles that make alanguage object-oriented:
0 Encapsulation
0 Data Abstraction
0 Polymorphism
0 Inheritance.
Chapter 1 - OOP Principles 66
The 4 basic Principles of OOP at a Glance(ct)
8/12/2019 Chapter 1 Overview of OOP
67/154
The 4 basic Principles of OOP at a Glance(ct)1. Encapsulation
Encapsulationis the hidingof dataimplementation by restricting
access to accessors and mutators. Encapsulation is the technique of making the fields in a class
private and providing access to the fields via public methods. If a
field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class. For this reason,
encapsulation is also referred to as data hiding.
Accessor : is a method that is used to ask an object about itself.
Accessor methods are any public method that gives information
about the state of the object.
Mutator: are public methods that are used to modify the state ofan object, while hiding the implementation of exactly how the data
gets modified.
Chapter 1 - OOP Principles 67
The 4 basic Principles of OOP at a Glance(ct)
8/12/2019 Chapter 1 Overview of OOP
68/154
p ( )1. Encapsulation (cont)
Class Person{
private String fullName = Abe Gubegna;
public String setFullName(String _fullName){
fullName = _fullName;
}
public String getFullName(){
return fullName;
}
}
So, the use of mutators and accessors provides many advantages. By
hiding the implementation of our Person class, we can make changes
to the Person class without the worry that we are going to break other
code that is using and calling the Person class for information.
This type of dataprotectionand implementationprotectionis called
Encapsulation. Chapter 1 - OOP Principles68
The 4 basic Principles of OOP at a Glance(ct)
8/12/2019 Chapter 1 Overview of OOP
69/154
e bas c c p es o OO at a G a ce(ct)
2. Abstraction
0 Data abstraction : is the development of classes, objects, types in terms of their
interfaces and functionality, instead of their implementation details.0 Abstraction denotes a model, a view, or some other focused representation for
an actual item. Its the development of a software object to represent an object
we can find in the real world. Encapsulation hides the details of that
implementation.
0 Abstraction is used to manage complexity. Software developers use abstractionto decomposecomplexsystemsintosmallercomponents.
0 An abstraction denotes the essential characteristics of an object that
distinguish it from all other kinds of object and thus provide crisply defined
conceptual boundaries, relative to the perspective of the viewer. G. Booch,
Object-Oriented Design With Applications, Benjamin/Cummings, Menlo Park,California, 1991.
0 In short, data abstraction is nothing more than the implementation of
an object that contains the same essential properties and actions we
can find in the original object we are representing.Chapter 1 - OOP Principles 69
The 4 basic Principles of OOP at a Glance(ct)
8/12/2019 Chapter 1 Overview of OOP
70/154
p ( )
3. Inheritance
0 Objects can relateto each other with either a has a, uses a or an is a
relationship.0 Is a is the inheritance way of object relationship. So, take a library, for
example. A library lends more than just books, it also lends magazines,
audiocassettes and microfilm. On some level, all of these items can be treated
the same: All four types represent assets of the library that can be loaned out to
people. However, even though the 4 types can be viewed as the same, they arenot identical. A book has an ISBN and a magazine does not. And audiocassette
has a play length and microfilm cannot be checked out overnight.
0 Each of these librarys assets should be represented by its own class
definition. Without inheritance though, each class must independently
implement the characteristics that are common to all loanable assets. All assets
are either checked out or available for checkout. All assets have a title, a date of
acquisition and a replacement cost.
0 Therefore rather than duplicating functionality, inheritance allows you to inherit
functionality from another class, called asuperclassor base class.70Chapter 1 - OOP Principles
The 4 basic Principles of OOP at a Glance(ct)
8/12/2019 Chapter 1 Overview of OOP
71/154
p ( )
4. Polymorphism
0 Polymorphismmeans one name, many forms.
0 Polymorphism manifests itself by having multiplemethodsall
with thesame name, but slightly different functionality.
0 There are 2 basic types of polymorphism, overriding and
overloading.
0 Overloading also called compile-time polymorphism: for
method overloading, the compiler determines which method will
be executed, and this decision is made when the code gets
compiled.
0 Overridingalso called run-time polymorphism : Which methodwill be used for method overriding is determined at runtime based
on the dynamic type of an object.
Chapter 1 - OOP Principles 71
1. Inheritance
8/12/2019 Chapter 1 Overview of OOP
72/154
0 The idea of inheritance is simple but powerful:
When you want to create a new class and there is already a class that includes some
of the code that you want, you can derive your new class from the existing class.
In doing this, you can reuse the fields and methods of the existing class withouthaving to write (and debug!) them yourself.
0 OOP allows classes to inheritcommonly used state and behavior from other classes.
0 Inheritance is one of the cornerstones of object-oriented programming because it allows the
creation of hierarchical classifications.
0 Using inheritance, you can create a general class that defines traits common to a set of related
items. This class can then be inherited by other, more specific classes, each adding those
things that are unique to it.
0 In the terminology of Java, a class that is inherited is called asuperclass. The class that does
the inheriting is called asubclass. Therefore, a subclass is a specialized version of a superclass.
It inherits all of the instance variables and methods defined by the superclass and adds its
own, unique elements.
0 In Java, each class is allowed to have onedirect superclass, and each superclass has the
potential for an unlimitednumber of subclasses.
0 A subclass inherits all the members(fields, methods, and nested classes) from its superclass.
0 Constructors are notmembers, so they are not inherited by subclasses, but the constructor of
the superclass can be invokedfrom the subclass. 72
1 Inheritance(cont)
8/12/2019 Chapter 1 Overview of OOP
73/154
1. Inheritance(cont)0 The syntax for creating a subclass, use the extendskeyword,
followed by the name of the class to inherit from:
classSuperClassName{
//fields and methods of the super class
}
classSubClassName extendsSuperClassName{// new fields and methods other than super class
}
Chapter 1 - OOP Principles 73
1 Inheritance(cont)
8/12/2019 Chapter 1 Overview of OOP
74/154
1. Inheritance(cont)0 Subclass: A class that is derived from another class. Also called a
derived class, extended class, or child class
0 Superclass: The class from which the subclass is derived. Also a
base classor aparent class.
0 Except Object, which has nosuperclass, every class has one and
only one direct superclass (single inheritance).
0 In the absenceof any other explicit superclass, every class is
implicitly a subclass of Object.
0 Classes can be derived from classes that are derived from classes,
and so on, and ultimately derived from the topmost class, Object.
Chapter 1 - OOP Principles 74
1. Inheritance(cont)
8/12/2019 Chapter 1 Overview of OOP
75/154
1. Inheritance(cont)0 The Objectclass, defined in the java.lang package, defines and
implements behavior common to all classesincluding the ones
that you write.
0 In the Java platform, many classes derive directly from Object,
other classes derive from some of those classes, and so on, forming
a hierarchy of classes.
0 At the top of the hierarchy, Object is the most general of all classes.Classes near the bottom of the hierarchy provide more specialized
behavior
Chapter 1 - OOP Principles 75
1. Inheritance(cont) classSimpleInheritance {publicstaticvoidmain(String args[]) {
http://java.sun.com/javase/6/docs/api/java/lang/Object.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/Object.html8/12/2019 Chapter 1 Overview of OOP
76/154
76
Example :
// Create a superclass.
classA {
inti, j;voidshowij() {
System.out.println("i and j: "+ i + " "+j);
}
}
// Create a subclass by extending class A.classB extendsA {
intk;
void showk() {
System.out.println("k: " + k);
}
voidsum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("superOb Contents :");
superOb.showij();
System.out.println();
/* The subclass has access to all publicmembers of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println(subOb Contents : ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k insubOb:");
subOb.sum();
}
}Chapter 1 - OOP Principles
1. Inheritance(cont)0 The output from this program is shown here:
8/12/2019 Chapter 1 Overview of OOP
77/154
0 The output from this program is shown here:Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9Sum of i, j and k in subOb:
i+j+k: 24
0 As you can see, the subclass B includes all of the members of itssuperclass, A. Thisis why subOb can access i and j and call showij( ).Also, inside sum( ), i and j can be referred to directly, as if they were
part of B.0 Even thoughA is a superclass for B, it is also a completely
independent, stand-alone class. Being a superclass for a subclass doesnot mean that the superclass cannot be used by itself. Further, a subclasscan be a superclass for another subclass.
0 You can only specify one superclass for any subclass that you create. Javadoes not support the inheritance of multiple superclasses into a singlesubclass. (This differs from C++, in which you can inherit multiple baseclasses.) You can, as stated, create a hierarchy of inheritance in which asubclass becomes a superclass of another subclass. However, no class can
be a superclass of itself.
77Chapter 1 - OOP Principles
1. Inheritance(cont)0 Although a subclass
includes all of
8/12/2019 Chapter 1 Overview of OOP
78/154
Chapter 1 - OOP Principles 78
0 Although a subclass includes all of
the members of its superclass, it
cannot access those members of
the superclass that have beendeclared as private. For example,
consider the following simple
class hierarchy:
Example :
// Create a superclass.
classA {
inti; // public by default
privateint j; // private to A
voidsetij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
classB extendsA {
inttotal;
voidsum() {total = i + j;
// ERROR, j is not accessible here
}
}
classAccess {
publicstaticvoidmain(Stringargs[]){
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();System.out.println("Total is " +subOb.total);
}}
1. Inheritance(cont)
8/12/2019 Chapter 1 Overview of OOP
79/154
( )0 This program will not compile because the reference to j inside
the sum( ) method of B causes an access violation. Since j is
declared as private, it is only accessibleby other members of its
own class. Subclasses have noaccess to it.
0 A class member that has been declared as privatewill remain
privateto its class. It is not accessible by any code outside its
class, including subclasses.
Chapter 1 - OOP Principles 79
8/12/2019 Chapter 1 Overview of OOP
80/154
8/12/2019 Chapter 1 Overview of OOP
81/154
1. In eritance contA Superclass Variable Can Reference a Subclass Object
8/12/2019 Chapter 1 Overview of OOP
82/154
A Superclass Variable Can Reference a Subclass Object
Chapter 1 - OOP Principles
82
0 A reference variable of a superclass can be assigned a reference toany subclass derived from that superclass. You will find this aspect
of inheritance quite useful in a variety of situations. For example,consider the following:
class SubClassExample {
publicstaticvoidmain(Stringargs[]) {
Cyliner cyl = new Cylinder(2, 4);
Circle cir = new Circle();
System.out.println(Sub Class Method call :);
cyl. displayAreaOfCylinder());
// assign Cylinder reference to Circle reference
cir = cyl;System.out.println(Super Class Method call :" );
cyl. displayAreaOfCircle());
// cir.height; //is invalid because cir doesnt define the height.
} }
1. Inheritance(cont)Using super
8/12/2019 Chapter 1 Overview of OOP
83/154
Using super
83
0 In the preceding examples, classes derived from Circle were not
implemented as efficiently or as robustly as they could have been.
0 For example, the constructor for cyl explicitly initializes the radius fieldof Circle( ). Not only does this duplicate code found in its superclass,
which is inefficient, but it implies that a subclass must be granted access
to these members.
0 However, there will be times when you will want to create a superclass
that keeps the details of its implementation to itself (that is, that keepsits data members private). In this case, there would be no way for a
subclass to directly access or initialize these variables on its own.
0 Since encapsulation is a primary attribute of OOP, it is not surprising that
Java provides a solution to this problem. Whenever a subclass needs to
refer to its immediate superclass, it can do so by use of the keyword
super.
0 superhas two general forms. The first calls the superclass constructor.
The second is used to access a member of the superclass that has been
hiddenby a member of a subclass.
Chapter 1 - OOP Principles
. n er tance cont Using super Use 1(cont)
8/12/2019 Chapter 1 Overview of OOP
84/154
Using super-Use 1(cont)
Chapter 1 - OOP Principles 84
0 A subclass can call a constructor method defined by its superclassby use of the following form of super:
super(parameter-list);0 Here,parameter-list specifies any parameters needed by the
constructor in the superclass. super( ) must always be the firststatement executed inside a subclass constructor.
0 To see how super()is used, consider this improved version of theCylinder( ) class:publicclassCylinder extendsCircle{
doubleheight;//constructor for Cylinder which initialize radius using super()Cylinder(double rad, double hei){
super(rad); // call to super class constructorheight = hei;}voiddisplayAreaOfCylinder(){
System.out.println(Area of the cylinder is: + (Math.PI* r * r * h));
}
}
. n er tance cont Using super-Use 2(cont)
8/12/2019 Chapter 1 Overview of OOP
85/154
Using super-Use 2(cont)
Chapter 1 - OOP Principles 85
0 The second form of superacts somewhat like this, except that it
always refers to the superclass of the subclass in which it is used.
This usage has the following general form:
super.member
0 Here, membercan be either a methodor an instance variable.
0 This second form of super is most applicable to situations in whichmember names of a subclass hide members by the same name in
the superclass. Consider this simple class hierarchy:
. n er tance cont Using super-Use 2(cont)
8/12/2019 Chapter 1 Overview of OOP
86/154
Using super-Use 2(cont)
Chapter 1 - OOP Principles 86
// Using super to overcome name hiding.
classA {
inti;
}
// Create a subclass by extending class A.
classB extendsA {
inti; // this i hides the i in A
B(inta, intb) {
super.i = a; // i in A
i = b; // i in B
}
voidshow() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}classUseSuper {
publicstaticvoidmain(Stringargs[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
1. Inheritance(cont)
8/12/2019 Chapter 1 Overview of OOP
87/154
( )Creating a Multilevel Hierarchy
Chapter 1 - OOP Principles 87
0 Up to this point, we have been using simple class hierarchies thatconsist of only a superclass and a subclass. However, you can build
hierarchies that contain as many layers of inheritance as you like.
0 It is perfectly acceptable to use a subclass as a superclass of
another. For example, given three classes called A, B, and C, C can
be a subclass of B, which is a subclass of A.
0 When this type of situation occurs, each subclass inherits all of the
traits found in all of its superclasses. In this case, C inherits all
aspects of B and A.
1. Inheritance(cont)
8/12/2019 Chapter 1 Overview of OOP
88/154
When Constructors Are Called
Chapter 1 - OOP Principles 88
0 When a class hierarchy is created, in what order are the
constructors for the classes that make up the hierarchy called?
0 For example, given a subclass called B and a superclass called A, is
As constructor called before Bs, or vice versa?
0 The answer is that in a class hierarchy, constructorsare calledin
orderofderivation, fromsuperclass to subclass.
0 Further, since super( ) must be the first statement executed in a
subclass constructor, this order is the same whether or not super()
is used. If super( ) is not used, then the default or parameterless
constructor of each superclass will be executed. Eg:-
. n er tance cont When Constructors Are Called(cont)
8/12/2019 Chapter 1 Overview of OOP
89/154
When Constructors Are Called(cont)
Chapter 1 - OOP Principles 89
// Demonstrate when constructors are called.
// Create a super class.
classA {
A() {System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
classB extendsA {
B() {
System.out.println("Inside B's constructor.");}
}
// Create another subclass by extending B.
classC extendsB {
C() {
System.out.println("Inside C's constructor.");
}}
classCallingCons {
public static void main(String args[]) {
C c = new C();
}
}
0 The output from this program isshown here:
Inside As constructorInside Bs constructor
Inside Cs constructor0 As you can see, the constructors
are called in order of derivation. If
you think about it, it makes sensethat constructors are executed inorder of derivation. Because asuperclass has no knowledge ofany subclass, any initialization itneeds to perform is separate fromand possibly prerequisite to any
initialization performed by thesubclass. Therefore, it must beexecuted first.
2. PolymorphismM th d O idi
8/12/2019 Chapter 1 Overview of OOP
90/154
Method Overriding0 In a class hierarchy, when a method in a subclass has the
same name and type signature as a method in its superclass,then the method in the subclass is said to overridethe
method in the 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.
0 The version of the method defined by the superclass will be
hidden. Consider the following:
Chapter 1 - OOP Principles 90
2. Polymorphism(cont)M th d O idi ( t)
8/12/2019 Chapter 1 Overview of OOP
91/154
Method Overriding(cont)
Chapter 1 - OOP Principles 91
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;}
void show() { // display i and j
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
92/154
Method Overriding(cont)0 The output produced by this program is shown here:
k: 3
0 When show( ) is invoked on an object of type B, the version of
show( ) defined within B is used. That is, the version of show( )
inside B overrides the version declared in A.
0 If you wish to access the superclass version of an overriddenfunction, you can do so by using super. For example, in this
version of B, the superclass version of show( ) is invoked within
the subclass version. This allows all instance variables to be
displayed.
Chapter 1 - OOP Principles 92
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
93/154
Method Overriding(cont)
Chapter 1 - OOP Principles93
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); //calls A's show()
System.out.println("k: " + k);
}
0 If you substitute this version ofA
into the previous program, youwill see the following output:
i and j: 1 2
k: 3
0 Here, super.show( ) calls the
superclass version of show( ).0 Method overriding occurs only
when the names and the typesignatures of the two methods areidentical. If they are not, then the
two methods are simplyoverloaded.
0 For example, consider thismodified version of the precedingexample:
8/12/2019 Chapter 1 Overview of OOP
94/154
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
95/154
Method Overriding(cont)0 The output produced by this program is shown here:
This is k: 3
i and j: 1 2
0 The version of show( ) in B takes a string parameter. This makes
its type signature different from the one in A, which takes no
parameters. Therefore, no overriding (or name hiding) takesplace.
Chapter 1 - OOP Principles 95
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
96/154
Method Overriding(cont)Why Overridden Methods?0 As stated earlier, overridden methods allow Java to support run-time
polymorphism.
0 Polymorphism is essential to object-oriented programming for onereason: it allows a general class to specify methods that will be commonto all of its derivatives, while allowing subclasses to define the specificimplementation of some or all of those methods.
0 Overridden methods are another way that Java implements the oneinterface, multiple methods aspect of polymorphism.
0 Part of the key to successfully applying polymorphism is understandingthat the superclasses and subclasses form a hierarchy which movesfrom lesser to greater specialization.
0 Used correctly, the superclass provides all elements that a subclass canuse directly. It also defines those methods that the derived class mustimplement on its own. This allows the subclass the flexibility to defineits own methods, yet still enforces a consistent interface. Thus, bycombining inheritance with overridden methods, a superclass candefine the general form of the methods that will be used by all of its
subclasses.
96
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
97/154
Method Overriding(cont)Using final with Inheritance
0 The keyword finalhas three uses. First, it can be used to createthe equivalent of a named constant. The other two uses of final
apply to inheritance.
First Use : Using final to Prevent Overriding
0 While method overriding is one of Javas most powerful
features, there will be times when you will want to prevent it
from occurring. To disallow a method from being overridden,
specify finalas a modifier at the start of its declaration.
Methods declared as final cannot be overridden. The followingfragment illustrates final:
Chapter 1 - OOP Principles 97
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
98/154
Method Overriding(cont)Example on First Use
classA {finalvoiddisplay() {
System.out.println("This is a final method.");
}
}
classB extendsA {
voiddisplay() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
0 Because display( ) is declared as final, it cannot beoverridden in B. If you attempt to do so, a compile-time errorwill result.
Chapter 1 - OOP Principles 98
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
99/154
Method Overriding(cont)Second Use : Using final to Prevent Inheritance
0 Sometimes you will want to prevent a class from beinginherited. To do this, precede the class declaration with final.
0 Declaring a class as final implicitly declares all of its methods
as final, too. As you might expect, it is illegalto declare a
class as both abstractand finalsince an abstract class is
incomplete by itself and relies upon its subclasses to provide
complete implementations.
99
2. Polymorphism(cont)Method Overriding(cont)
8/12/2019 Chapter 1 Overview of OOP
100/154
Method Overriding(cont)final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A// ...
}
0 As the comments imply, it is illegal for B to inherit A since A
is declared as final.
Chapter 1 - OOP Principles 100
2. Polymorphism(cont)The Object Class
8/12/2019 Chapter 1 Overview of OOP
101/154
The Object Class0 There is one special class, Object, defined by Java.
0 All other classes are subclasses of Object. That is, Object is asuperclass of all other classes. This means that a reference
variable of type Object can refer to an object of any other class.
Also, since arrays are implemented as classes, a variable of type
Object can also refer to any array.0 Object defines the following methods, which means that they are
available in every object.
Chapter 1 - OOP Principles 101
Method Purpose
8/12/2019 Chapter 1 Overview of OOP
102/154
Object clone( ) Creates a new object that is the same as
the object being cloned.
boolean equals(Object object) Determines whether one object is equal to
another.
void finalize( ) Called before an unused object is
recycled.
Class getClass( ). Obtains the class of an object at run time
int hashCode( ) Returns the hash code associated with the
invoking object.
void notify( ) Resumes execution of a thread waiting on
the invoking object.
String toString( ) Returns a string that describes the object.Chapter 1 - OOP Principles 102
3.Abstract Classes
8/12/2019 Chapter 1 Overview of OOP
103/154
0Abstractionrefers to the ability to make a class abstract in OOP.
An abstract class is one that cannotbeinstantiated. All otherfunctionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot
create an instance of the abstract class.
0 This is typically how abstract classes come about during thedesign phase. A parent class contains the common functionality of
a collection of child classes, but the parent class itself is too
abstract to be used on its own.
0 Use the abstractkeyword to declare a class abstract. The
keyword appears in the class declaration somewhere before the
class keyword.
Chapter 1 - OOP Principles 103
3.Abstract Classes(cont)
8/12/2019 Chapter 1 Overview of OOP
104/154
0 There are situations in which you will want to define a superclassthat declares the structure of a given abstraction without providing
a complete implementation of every method. That is, sometimes youwill want to create a superclass that only defines a generalizedform that will be shared by all of its subclasses, leaving it to eachsubclass to fill in the details.
0 Such a class determines the nature of the methods that the
subclassesmust implement. One way this situation can occur iswhen a superclass is unable to create a meaningfulimplementation for a method.
0 You can require that certain methods be overridden by subclasses
by specifying the abstract type modifier. These methods aresometimes referred to assubclasser responsibility because theyhave no implementation specified in the superclass. Thus, a subclassmust override themit cannot simply use the version defined inthe superclass. Chapter 1 - OOP Principles 104
3.Abstract Classes(cont)bli b t t l E l {
8/12/2019 Chapter 1 Overview of OOP
105/154
public abstract class Employee {
private String name;
private String jobTitle;public Employee(String name, String jobTitle) {
this.name = name;
this. jobTitle = jobTitle;
}
public void getEmployee(){
System.out.println(Employee Info);
System.out.println(Name : + name + JobTitle : + jobTitle);
}
}0 Notice that nothing is different in this Employee class. The class is now
abstract, but it still has two fields, one methods, and one constructor.
0 Now if you would try as follows:Chapter 1 - OOP Principles 105
3.Abstract Classes(cont)bl l b {
8/12/2019 Chapter 1 Overview of OOP
106/154
public class AbstractDemo {
public static void main(String [] args) {
Employee e = new Employee(Tenagne", Secretary);
}
}
0 When you would compile above class then you would get
following error: Employee is abstract; cannot be instantiated
Employee e = new Employee(Tenagne", Secretary);
Chapter 1 - OOP Principles 106
3.Abstract Classes(cont)Extending Abstract Class:
8/12/2019 Chapter 1 Overview of OOP
107/154
Extending Abstract Class:0 We can extend Employee class in normal way as follows:
public class Salary extendsEmployee {
private double salary;
public Salary(String name, String jobTitle, double salary){
super(name, jobTitle);
setSalary(salary);
}public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {salary = newSalary;
}
}
} Chapter 1 - OOP Principles 107
8/12/2019 Chapter 1 Overview of OOP
108/154
3.Abstract Classes(cont)Al h h b l b d i i
8/12/2019 Chapter 1 Overview of OOP
109/154
0 Although abstract classes cannot be used to instantiate
objects, they can be used to create object references,
because Javas approach to run-time polymorphism isimplemented through the use of superclass references.
Thus, it must be possible to create a reference to an
abstract class so that it can be used to point to a subclass
object.
Chapter 1 - OOP Principles 109
.Abstract Classes(cont)Abstract Methods
8/12/2019 Chapter 1 Overview of OOP
110/154
0 If you want a class to contain a particular method but you want theactual implementation of that method to be determined by child
classes, you can declare the method in the parent class as abstract.0 The abstract keyword is also used to declare a method as abstract.
An abstract methods consist of a methodsignature, but nomethod body.
0 Abstract method would have no definition, and its signature is
followed by a semicolon, not curly braces.0 To declare an abstract method, use this general form:
abstracttype name(parameter-list);
0 As you can see, no method body is present.
0 Any class that contains one or more abstract methods mustalso bedeclared abstract. To declare a class abstract, you simply use theabstract keyword in front of the class keyword at the beginning ofthe class declaration. There can be no objects of an abstract class.That is, an abstract class cannot be directly instantiated with thenew operator. Such objects would be useless, because an abstract
class is not fully defined.
110
.Abstract Classes(cont)Abstract Methods(cont)
8/12/2019 Chapter 1 Overview of OOP
111/154
( )0 Also, you cannotdeclare abstract constructors, or abstract
static methods.
0 Any subclass of an abstract class musteither implementall of
the abstract methods in the superclass, or be itself declared
abstract.
0 Example:public abstract class Employee {
private String name;
private String jobTitle;
public abstract double computeTax();
//Remainder of class definition
} Chapter 1 - OOP Principles 111
.Abstract Classes(cont)Abstract Methods(cont)
8/12/2019 Chapter 1 Overview of OOP
112/154
( )
0 Declaring a method as abstract has two results:
0 The class must also be declared abstract. If a class contains anabstract method, the class must be abstract as well.
0 Any child class must either override the abstract method or
declare itself abstract.
0 A child class that inherits an abstract method mustoverride it. If they do not, they must be abstract, and any
of their children must override it.
0 Eventually, a descendant class has to implement the
abstract method; otherwise, you would have a hierarchy
of abstract classes that cannot be instantiated.
Chapter 1 - OOP Principles 112
.Abstract Classes(cont)Abstract Methods(cont)
8/12/2019 Chapter 1 Overview of OOP
113/154
( )
0 If Salary is extending Employee class then it is required to
implement computeTax() method as follows:
public class Salary extends Employee {
private double salary;
public double computeTax() {
return (salary * 0.35);
}
//Remainder of class definition
}Chapter 1 - OOP Principles 113
3.2.Interfacesf ll f b h d
8/12/2019 Chapter 1 Overview of OOP
114/154
0 An interface is a collectionof abstractmethods.
0 A class implementsan interface, thereby inheriting the abstract
methods of the interface.0 An interface is notaclass. Writing an interface is similar to writing
a class, but they are two different concepts.
0 A class describesthe attributes and behaviors of an object. An
interface containsbehaviors that a class implements.0 Unlessthe class that implements the interface is abstract, all the
methods of the interface need to be definedin the class.
In Java, a class can inherit from only one class but it can implement
more than one interface.
Chapter 1 - OOP Principles 114
8/12/2019 Chapter 1 Overview of OOP
115/154
3.2.Interfaces(cont)0 A i t f i i il t l i th f ll i
8/12/2019 Chapter 1 Overview of OOP
116/154
0 An interface is similar to a class in the following ways:
1. An interface can contain any number of methods.
2. An interface is written in a file with a .javaextension, with the name ofthe interface matching the name of the file.
3. The bytecode of an interface appears in a .classfile.
4. Interfaces appear in packages, and their corresponding bytecode filemust be in a directory structure that matches the package name.
0However, an interface is different from a class in several ways,including:
1. You cannot instantiate an interface.
2. An interface does not contain any constructors.
3. All of the methods in an interface are abstract.
4. An interface cannot contain instance fields. The only fields that canappear in an interface must be declared both static and final.
5. An interface is not extended by a class; it is implemented by a class.
6. An interface can extend multiple interfaces.
Chapter 1 - OOP Principles 116
3.2.Interfaces(cont)D l i I f
8/12/2019 Chapter 1 Overview of OOP
117/154
Declaring Interfaces:
0 The interfacekeyword is used to declare an interface.
0 Encapsulation can be described as a protective barrier that
prevents the code and data being randomly accessed by other
code defined outside the class.
0 Access to the data and code is tightly controlled by an interface.
0 The main benefit of encapsulation is the ability to modify our
implemented code without breaking the code of others who use
our code. With this feature Encapsulation gives maintainability,
flexibility and extensibility to our code.
Chapter 1 - OOP Principles 117
3.2.Interfaces(cont)0 L t l k t l
8/12/2019 Chapter 1 Overview of OOP
118/154
0 Let us look at an example
public interfaceNameOfInterface {
//Any number of final, static fields//Any number of abstract method declarations
}
0 Interfaces have the following properties:
0 An interface is implicitly abstract. You do not need to use
the abstractkeyword when declaring an interface.
0 Each method in an interface is also implicitly abstract, so the abstract
keyword is not needed.
0 Methods in an interface are implicitly public.
0 Example:interfaceAnimal {
public void eat();
public void travel();
} Chapter 1 - OOP Principles 118
3.2.Interfaces(cont)I l ti I t f
8/12/2019 Chapter 1 Overview of OOP
119/154
Implementing Interfaces:
0 When a class implements an interface, you can think of the class as
signinga contract, agreeing to perform the specific behaviors of theinterface. If a class does not perform all the behaviors of the interface,
the class must declare itself as abstract.
0 A class uses the implementskeyword to implement an interface. The
implements keyword appears in the class declaration following the
extends portion of the declaration.
0 Implementing an interface allows a class to become more formal about
the behavior it promises to provide. Interfaces form a contract
between the class and