Objects & Classes, Advanced Programming
Objects & Classes, Advanced Programming
Objects & Classes, Advanced Programming
Fall 2018
Lecture 3-4
3
What are objects?
Real-world objects share two characteristics: They all have state and behavior.
Dogs have state (name, color, breed) and behavior (barking, fetching, wagging
tail). Bicycles also have state (current gear, current speed) and behavior
(changing gear, applying brakes).
4
Software Objects
Software objects are conceptually similar to real-world objects: they too
consist of state and related behavior. An object stores its state in fields or
variables and exposes its behavior through methods (functions in some
programming languages).
5
Advantages of using Objects?
Modularity
Information-hiding
Code re-use
6
Classes
A class is the blueprint from which individual objects are created.
Example
Each bicycle was built from the same set of blueprints and therefore
contains the same components.
7
Defining a Class
There are three kinds of things that you can include in a class definition
Data members also called variables, fields.
Member methods
Initialization blocks
An instance of a class is technical term for an existing object of that
class. So instantiation is making objects.
Data members
These are the variables that store data items that typically
differentiate one object of a class from another.
Variables in a class definition are not the same, there are two kinds
Instance variable
Class variables
8
Variables
Instance variable are those variables that are associated with
each object uniquely.
Each instance of the class will have its own copy of each of these
variables.
Each object will have its own values for each instance variables that
differentiate one object from the other of the same class type.
Declared in the usual way and can have an initial value specified.
Class variables are associated with the class and is shared by
all objects of the class.
There is only one copy of each of these variables no matter how many
class objects are created.
They exist even if no objects of class have been created.
These variables are also called static fields because we use the keyword
static when we declare them.
9
Variables
Why would you need two kinds of variables in a class
definition?
One use of class variables is to hold constant values that are
common to all the objects of the class
Another use is to track data values that are common to all
objects and that need to be available even when no objects
have been defined. Like keeping count of no of objects
created in the program
10
PI = 3.14
public class Sphere{
globe
xCenter
// class variable yCenter
Static double PI = 3.14; zCenter
radius
11
Methods
Member Methods
These define the operations you can perform for the class, typically
on the variables of the class
There are two kinds of methods
Instance methods
Class methods
12
Methods
Instance Methods
These methods can only be executed in relation to a particular object
Note: Although instance methods are specific to objects of a class, there is only one
copy of an instance method in memory that is shared by all the objects of the class.
Class Methods
You can execute class methods even when no objects of a class exist.
Like class variables, these are declared using the keyword static, so also called
static methods
Static methods cannot refer to instance variables or call instance methods. Why?
13
Defining a Class
Defining Classes
Use the keyword class followed by the name of the class followed by a
pair of braces enclosing the details of the definition.
Member variables get initialized to default values if we don’t
initialize them explicitly
Numeric fields initialized with zero, char fields with ‘\u0000’, boolean
with false and fields references are initialized with null
14
Defining Classes
Accessing Variables and Methods
How can we access variables and methods defined within a class
from outside it?
Accessibility is different for instance and static members
For Static members, we have got two choices
Use class name followed by a dot operator followed by the static
member name i.e Math.sqrt(Math.PI);
If reference to an object of the class type is available,then use
reference name followed by dot operator, followed by the member
name.
For Instance members
They can be called only through the object reference
15
Defining Classes
Class Declaration
class MyClass {
//field, constructor, and method declarations
}
The class body (the area between the braces) contains all the code that provides for the life
cycle of the objects created from the class:
constructors for initializing new objects,
declarations for the fields that provide the state of the class and its objects,
and methods to implement the behavior of the class and its objects.
16
Declaring Variables
Variable declarations are composed of three components, in
order:
Zero or more modifiers, such as public or private.
The variable’s type.
The variable's name.
17
Declaring Methods
Method declarations have six components, in
order:
Modifiers—such as public, private, and others you will learn about later.
The return type—the data type of the value returned by the method, or
void if the method does not return a value.
The method name
The parameter list in parenthesis—a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty parentheses.
An exception list—to be discussed later.
The method body, enclosed between braces—the method's code,
including the declaration of local variables, goes here.
return_type method_name(arg1, arg2, …. , argn){
//code
}
18
Initialization Blocks
You can initialize data members with explicit values if you like,
but in case initialization involves some calculations then you
have to use initialization blocks
An initialization block is a block of code between braces that is
executed before an object of the class is created.
There are two kinds of initialization blocks
Static initialization block
Non-static initialization block
19
Initialization Blocks
Static initialization block
Is a block defined using the keyword static
It is executed once when the class is loaded.
It can only initialize static data members of the class
Non-static initialization block can initialize both static and no- static
data members
Normally you don’t initialize static data members using non-static
initialization block
This block is executed each time an object is instantiated
20
Static Initialization Block Example
class TryInitialization
{
static int[] values = new int[10]; // Static array member
// Initialization block
// static
{
System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random());
}
// List values in the array for an object
void listValues()
{
System.out.println(); // Start a new line
for(int i=0; i<values.length; i++)
System.out.print(" " + values[i]); // Display values
21
public static void main(String[] args)
{
TryInitialization example = new TryInitialization(); System.out.println("\nFirst object:");
example.listValues();
22
Non-Static Init Block
class TryInitialization
{
static int[] values = new int[10]; // Static array member
// Initialization block
{
System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random());
}
23
Constructor
When you create an object of a class, a special kind of method
called a constructor is always invoked.
If you don’t define any constructor, the compiler will supply a default
constructor in the class that does nothing
24
Constructor
A constructor can have any number of parameters including none
A constructor is called with new keyword when we make object of any
class.
If we define a constructor, then default constructor is not provided by
the compiler
You can have multiple constructors for your class
Any initialization blocks that you have defined in a class are always
executed before the constructor
25
class Sphere
{
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Class constructor
Sphere(double theRadius, double x, double y, double z)
{
26
// Static method to report the number of objects created
{
return count; // Return current object count
double volume()
{
return 4.0/3.0*PI*radius*radius*radius;
}
27
Multiple Constructors
// Class constructor
Sphere(double theRadius, double x, double y, double z)
{
radius = theRadius; // Set the radius
28
Creating Objects of a Class
Declare the object
Sphere ball;
Creating an Object
You must use keyword new followed by the constructor
ball = new Sphere(); or
ball = new Sphere (10,1.0,1.0,1.0);
29
public class CreateSpheres
{
public static void main(String[] args)
{
System.out.println("Number of objects = " + Sphere.getCount());
30
Garbage Collection
Objectsare dynamically allocated
How are these destroyed?
Answer: Garbage Collection
Automatic – occurs if objects exist and are no longer in use
If you create huge objects -> System.gc();
31
Method Overloading
Defining several methods in a class with the same name as long as each
method has a set of parameters that is unique is called method overloading
The signature – name of method, type and order of the parameters must be
unique for each method
Constructors can also be overloaded ( You can have multiple constructors for a
class)
32
this variable
Each object of the class have its own separate set of instance
variables, but same instance methods
As there is only one copy of each instance method for a class, variable
this allows the same method to work for different class objects
The variable this
Every instance method has a variable with the name this which refers to the
current object for which the method is called
this is used implicitly by the compiler when your instance method refers to an
instance variable of the class.
Each time an instance method is called , the this variable is set to reference the
particular class object to which it is being applied
33
Exercises
1. Consider the following class:
public class IdentifyMyParts {
public static int x = 7;
public int y = 3;
}
a.What are the class variables?
b.What are the instance variables?
34
What is the output?
IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new
IdentifyMyParts();
a.y = 5;
b.y = 6; IdentifyMyParts.x = 1;
b.x = 2;
System.out.println("a.y = " + a.y);
System.out.println("b.y = " + b.y);
System.out.println("IdentifyMyParts.x = " + a.x);
System.out.println("b.x = " + b.x);
35
Output
a.y = 5
b.y = 6
IdentifyMyParts.x = 2
b.x = 2
36
Exercise
Create a class rectangle. The instance variables are length and width.
Write a constructor to set the values for length and width to 1.
Write a second constructor that takes 2 arguments length, width.
Write get and set methods to get and set the values of instance variables.
Write methods to calculate perimeter and area.
Create two objects using two different constructors in the main method
Print the perimeters and areas for both rectangles.
37
The finalize() method
Sometimes an object will need to perform some action
when it is destroyed
Forexample, when it is holding some non-java resource like a file or windows font
We want to make sure that they are released before an object is destroyed
Finalization
We can define specific actions that occur when an object is just about to be
destroyed
Done using the finalize() method
protected void finalize(){
}
It is called by JVM before any object is destroyed.
38
Nested Classes
You can put the definition of one class inside the definition of
another class. The inner class is called a nested class
A top level class is a class that contains a nested class but is not
itself a nested class
A nested class can itself have another class nested inside it and
so on
public class Outside{
public class Inside {
//detail of nested class
}
//more members of Outside class
}
39
Why Use Nested Classes?
It is a way of logically grouping classes that are only used in one place.
40
Nested Classes
The nested class is a member of the top level class
The nested class can access attributes just like other class
members
When you declare an object of a class containing a nested
class, no objects of the nested class are created unless the
constructor of the enclosing class does so.
Outside outer = new Outside( );
Outside.Inside inner = outer.new Inside ( );
You must refer to the nested class type using the name of the
class as qualifier, but within non-static methods that are
members of Outside, you can use the nested class name
without any qualification
Inside inner=new Inside( );
41
Nested Classes
Static methods cannot create objects of a non-static nested class
To make objects of a nested class type independent of the objects
of the enclosing class, what can we do?
Declare the nested class as static
42
Packages and Access
Modifiers
43
FAST – NUCES 2018 44
Uses of packages
To create different class name spaces
Names used for classes in one package will not interfere with the names
of classes in another package
45
Creating packages
Add a package statement as the first statement in your source file containing
the class definition
Only comments and blank lines are allowed to precede the package statement
A package statement consist of the keyword package followed by the package
name terminated by a semicolon.
You can specify a package name as a sequence of names separated by
periods.
Packages are intimately related to the directory structure in which they are
stored
Class files must be in a directory named by the package
46
Accessing packages
Jdk1.4
c:\jdk1.4
code
package code.p1;
Use
import code.*; public
Circle class Use { }
47
Importing classes
There are two ways to use classes in other packages provided they
are defined public
Use fully qualified class name
Import the class. This allows you to use just the class name
You can import any or all of the classes in a package to your code by
using the import statement
Keyword import is followed by name of class/classes you want to import
terminated by a semicolon.
e.g. import java.io.*;
48
Automatic imports
Two packages are automatically imported in your source code. You don’t
need to write explicit import statements for them
java. lang.*
49
Accessing packages
Put the source code for a class, interface, enumeration, or
annotation type in a text file whose name is the simple name
of the type and whose extension is .java
// in the Rectangle.java file package graphics;
public class Rectangle() { . . . }
Then, put the source file in a directory whose name reflects the
name of the package to which the type belongs:
.....\graphics\Rectangle.java
class name graphics.Rectangle
pathname to file graphics\Rectangle.java
50
Accessing packages
When you compile a source file, the compiler creates a different
output file for each type defined in it. The base name of the output
file is the name of the type, and its extension is .class.
// in the Rectangle.java file
package com.example.graphics;
<path_one>\sources\com\example\graphics\Rectangle.java
<path_two>\classes\com\example\graphics\Rectangle.class
By doing this, you can give the classes directory to other programmers
without revealing your sources
52
Access Modifiers
Modifiers are java keywords that give the compiler
information about the nature of code, data or classes
Modifiers controls access to features
Features are
The class itself
Its variables
Its methods ( including constructors)
53
Access Modifiers
A feature may have at most one access modifier
Each access modifier controls the access for only that particular feature
What happens in C++?
Java provides a default access which is used when no access modifier is
present. Any class, field, method or constructor that has no declared access
modifier is
accessible only by classes in the same package
The only variables that may be controlled by access modifiers are class level
variables
Local variables may not have access modifiers
54
Access Modifiers
Public Access Modifiers are most generous
These Access Modifiers are available to the class itself and to any other
class without any restriction
Can be applied to class, variable or method
Protected Access Modifiers can be applied to variables, methods and inner
classes only
Non-inner classes cannot be made protected
These are available to all classes in the same package AND
To all subclasses of the class that owns that protected feature
This access is provided even to subclasses that reside in a different
package from the class that owns the protected feature
55
Access Modifiers
Private Access Modifiers are of the most restricted kind.
Only variables and methods can be made private
A private feature can only be accessed by an instance of the class
An instance of a sub class of the class in question cannot access private
features
56
Access Modifiers
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
57
58
59
Access Modifier
60
Access Modifiers
There can be only one public class per compilation unit ( file). It
can have as many supporting classes as you want.
The name of the public class must exactly match the name of
the file including capitalization
It is possible to have a file with no public class at all. In this
case, you can name the file whatever you like
What happens in this case when you compile the file?
61
Other Modifiers
Modifiers are java keywords that give the compiler
information about the nature of code, data or classes
Other Modifiers are
final
static
abstract
native
transient
synchronized
volatile
62
Other Modifiers
Java does not care about order of appearance of modifiers
public static is same as static public ( in main method( ))
Not every modifier can be applied to every kind of feature
Some combinations of modifiers are not allowed
63
Final Modifier
Final modifier can be applied to classes, methods and variables
Final classes cannot be sub classed
Java.lang.Math class is final, you cannot make a subclass of Math class
64
Static Modifier
Static modifier can be applied to variables, methods and blocks
Static features belong to a class rather than associated with an individual
instance of the class
A static variable is also called class variable and can be referenced in two
ways
Via the class name
Via a reference to any instance of the class
A static method is also called a class method and it can only access static
features of the class
Static initialization block is executed at class load time in the order of
appearance
65
Abstract Modifier
Abstract modifier can be applied to classes and methods only
An abstract method has no body
abstract void sound( );
Any class which contains an abstract method must be declared as abstract
class
An abstract class cannot be instantiated
Abstract classes defer the implementation to subclasses
The subclass must provide the implementation of the abstract method or declare
itself to be abstract in which case the implementation is deferred once again
66
Abstract Modifier
A class must be declared abstract if any of the following condition
is true
The class has one or more abstract methods
The class inherits one or more abstract methods for which it does not
provide implementation
The class declares that it implements an interface but does not provide
implementation for every method of that interface
67
Native Modifier
Native modifier can be applied to methods only
A Native method indicates that the body of the method is to be found
elsewhere
native void sound( );
Unlike abstract in which the body is found in the subclass, the body of native
methods lies outside JVM in a library
Native code is written in a non-java language typically C/C++ and is
compiled for a single target machine
The standard API for implementing native methods in C is called JNI (
Java native Interface )
68
Synchronized Modifier
Synchronized modifier is used to control access to critical code in multi
threaded programs
It can only be applied to methods and local blocks within the methods
69
Modifiers
Modifier Class Variable Method Block
Native no no yes no
70
Abstract Classes and
Interfaces
71
Interfaces
An interface is a collection of constants and abstract methods
The methods in an interface are always public and abstract
The constants in an interface are always public static and final
You don’t need to specify these attributes for the methods and the constants
in the interface
To make use of an interface, you implement the interface in a class
You declare that the class implements the interface and you write code for
each of the methods declared in the interface as part of the class definition
Any constants in an interface are available to the class implementing that
interface
72
Example: Interface
public interface Conversions {
double inchesToMillimeters (double inches);
double ouncesToGrams(double ounces);
double poundsToGrams(double pounds);
double hpToWatts(double hp);
double wattsToHP(double watts);
}
73
Example: Interface Implementation
import static conversions.ConversionFactors.*; // Import static members
74
Example: Interface Implementation
public static void main(String args[]) {
int myWeightInPounds = 180;
int myHeightInInches = 75;
76
Extending Interfaces
You can also extend an interface
You can define one interface based on another by using the keyword extends to
identify the base interface name
To specify an interface that includes the members of several other interfaces,
specify the names of the interfaces, separated by commas following the keyword
extends
An interface can extend one or more interfaces but can not extend a class.
Similarly an interface can not implement anything.
77
Example: Extending an Interface
public interface DoIt {
void doSomething(int i, double x); int
doSomethingElse(String s);
} What is the
Problem
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x, String s);
}
79
Using Interfaces
Where several classes share a common set of methods with given
signatures but with possible different implementation, you can separate
the set of methods common to the class into an interface. This interface
can then be implemented by each of the class
For polymorphism to work, you need one variable that is capable of
referring to one of the different kind of object, as we don’t have a base
class now
We can use a variable of the interface type as we are using the
interface to specify the methods that are common to all the classes
Thus if you declare a variable to be an interface type, you can use it to
reference an object of any class that is declared to implement the
interface(barring abstract classes)
80
Example: Interface as Type
public interface Relatable {
81
Example: Interface as Type
public Object findLargest(Object object1, Object object2) {
if ( (obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2;
}
82
What’s the difference between an
interface and an abstract class in Java?
It’s best to start answering this question with a brief definition of abstract classes
and interfaces
and then explore the differences between the two.
83
/* the Figure class must be declared as abstract because it contains an abstract method */
84
In the Figure class above, we have an abstract method called getArea(), and
because the Figure class contains an abstract method the entire Figure class
itself must be declared abstract. The
85
Figure base class has two classes which derive from it – called Circle and Rectangle. Both the
Circle and Rectangle classes provide definitions for the getArea method, as you can see in the
code above.
But the real question is why did we declare the getArea method to be abstract in the Figure class?
Well, what does the getArea method do? It returns the area of a specific shape. But, because the
Figure class isn’t a specific shape (like a Circle or a Rectangle), there’s really no definition we can
give the getArea method inside the Figure class. That’s why we declare the method and the Figure
class to be abstract. Any classes that derive from the Figure class basically has 2 options: 1. The
derived class must provide a definition for the getArea method OR 2. The derived class must be
declared abstract itself.
Now that we’ve explored the abstract method/class concepts, let’s get into the concept of interfaces
and how they differ from abstract classes.
86
An interface differs from an abstract class because an interface is not a class. An interface is essentially a type that can
be satisfied by any class that implements the interface.
It must have the phrase "implements Interface_Name" at the beginning of the class definiton.
It must implement all of the method headings listed in the interface definition.
87
}
88
Now that we know the basics of interfaces and abstract classes, let’s get to the heart of the question and explore the differences between the two. Here
are the three major differences:
With an interface on the other hand, the relationship between the interface itself and the class implementing the interface is not necessarily strong. For
example, if we have a class called "House", that class could also implement an interface called "AirConditioning". Having air conditioning not really an
essential part of a House (although some may argue that point), and the relationship is not as strong as, say, the relationship between a “TownHouse”
class and the "House" class or the relationship between an “Apartment” class that derives from a “House” class.
Because a TownHouse is a type of House, that relationship is very strong, and would be more appropriately defined through inheritance instead of
interfaces.
So, we can summarize this first point by saying that an abstract class would be more appropriate when there is a strong relationship between the
abstract class and the classes that will derive from it. Again, this is because an abstract class is very closely linked to inheritance, which implies a
strong relationship. But, with interfaces there need not be a strong relationship between the interface and the classes that implement the interface.
89
Abstract classes can have some implementation code
3. An abstract class may provide some methods with definitions – so an abstract class can have non-abstract methods
with actual implementation details. An abstract class can also have constructors and instance variables as well. An
interface, however, can not provide any method definitions – it can only provide method headings. Any class that
implements the interface is responsible for providing the method definition/implementation.
Here are some guidelines on when to use an abstract class and when to use interfaces in Java:
An abstract class is good if you think you will plan on using inheritance since it provides a common base class
implementation to derived classes.
An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must
be public.
If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new
method headings to an interface, then all of the classes that already implement that interface will have to be changed to
implement the new methods. That can be quite a hassle.
Interfaces are a good choice when you think that the API will not change for a while.
Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement
multiple interfaces.
90
Inheritance &
Polymorphism
91
Inheritance
Defining a new class based on an existing class is called derivation
The derived class is also called the direct subclass of the base or super
class
You can also derive classes from the derived class and so on
Class A
Class B
Class C
92
Inheritance
class B extends A{
//definition of class B
}
The keyword extends identifies that class B is a direct subclass of class A
The class B can have additional members in addition to the inherited
members of class A
What are the inherited members?
The member which is accessible in the derived class
93
Example – Super Class
public class Animal
{
public Animal(String aType)
{
type = new String(aType);
}
94
Example – Sub Class
public class Dog extends Animal
{
public Dog(String aName)
{
// Call the base constructor
super("Dog");
// Supplied name
name = aName;
// Default breed value
breed = "Unknown";
}
public Dog(String aName, String aBreed)
{ // Call the base constructor
super("Dog");
// Name of a Dog
name = aName; breed = aBreed;
// Dog breed
}
private String name; // Supplied name
private String breed; // Supplied breed
}
95
Example: Test Derived
public class TestDerived
{
public static void main(String[] args)
{
Dog aDog = new Dog("Fido", "Chihuahua"); // Create a dog
Dog starDog = new Dog("Lassie"); // Create a Hollywood dog
System.out.println(aDog); // Let's hear about it
System.out.println(starDog); // and the star
}
}
96
Inheritance
The inclusion of members of a base class in a derived class so that they are
accessible in that derived class is called class inheritance
An inherited member of a derived class is a full member of that class and is
freely accessible to any method in the class
Which members of the base class are inherited?
97
98
Inheritance
You can define a data member in a derived class with the same name as
data member in the base class.
The data member of the base class is still inherited but is hidden by the
derived class member with the same name
The hiding will occur irrespective if the type or access modifiers are the same
or not.
Any use of the derived member name will always refer to the member
defined in derived class
To refer to the inherited base class member, you must qualify it with the
keyword super
99
Inheriting Methods
Methods in a base class excluding constructors are inherited in a derived
class in the same way as the data members of the base class
Methods declared as private in a base class are not inherited
Default access methods are only inherited if you define the derived class
in the same package as the base class
Note: Constructors in the base class are never inherited regardless of
their attributes
Though the base class constructors are not inherited in your derived
class, you can still call them or if you don’t call a base class constructor
from your derived class constructor, the compiler will try to do it for you
The super class constructor is called in a subclass using super ( );
100
Inheriting Methods
The super/base class constructor call must be the first statement in the
body of the derived class constructor
If the first statement in a derived class constructor is not a call to a base
class constructor, the compiler will insert a call to the default class
constructor i.e super ( ), for you
Default call for base class constructor is with no arguments. This
sometimes result in a compiler error.Why?
101
Overriding Methods
You can define a method in a derived class that has the same
signature as a method in the base class. In this case the method
defined in the derived class overrides the method in the base class
The base class method is still present in the derived class and it is
possible to call the base class method also
An overridden method can be called from within the subclass using
super.xx( ) where xx( ) is the method name
102
Example2
public class Dog extends Animal
{
public Dog(String aName)
{ // Call the base constructor
super("Dog"); name = aName; // Supplied name
breed = "Unknown"; // Default breed value
}
public Dog(String aName, String aBreed)
{
super("Dog"); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}
// Present a dog's details as a string
public String toString()
{
return "It's " + name + " the " + breed;
}
103
Overriding Methods
Same signature and return type
Each parent class method may be overridden at most once in any one
subclass
You cannot change the access attributes
method cannot be made more restrictive than that of the base class method it
overrides
104
Overriding vs Overloading
Overloaded methods supplement each other while an overriding method
replaces the method it overrides
Overloaded methods can exist in any number in the same class while
each method in a base class can be overridden at the most once in any
one class
Overloaded methods must have different parameter lists while overriding
methods must have identical type and order of the parameter list
The return type of an overloaded method can be chosen freely while the
return type of an overriding method must be identical to that of the method
it overrides
105
Polymorphism
Poly means many and morph many forms. The word polymorphism
means the ability to assume different forms or shapes.
In programming terms, it is the ability of a single reference variable of
a given type to be used to reference objects of different types and to
automatically call the method that is specific to the type of object the
variable references
So a single method call behaves differently depending on the type of
the object which the call references
106
Polymorphism
We can store a reference to an object in a variable of the same type
We can store a reference to a derived class object in a variable of the
derived class type AND we can also store it in a variable of any direct or
indirect base class
To be able to support polymorphic behavior, there are a few requirements
The method call for the derived class object must be through a variable of
a base class object
The method called must also be a member of the base class
The method being used must satisfy all requirements for overridden
methods
107
Example – Polymorphism
public class Animal
{
public Animal(String aType)
{
type = new String(aType);
}
109
Example – Polymorphism
// Return a String full of a cat's details
// A miaowing method
public void sound()
{
System.out.println("Miiaooww");
}
110
111
112
113
Polymorphism
When you call a method using a variable of a base class type,
polymorphism results in the method that is called being selected based on
the type of the object stored, not the type of the variable
114
Polymorphism
Polymorphism only applies to methods
When you access a data member of a class object, the variable type
always determines the class to which the data member belongs
115
Universal Superclass
All classes you define are subclasses by default
All classes have a standard class Object as the base class
You don’t have to specify this, its implicit
As Object is a super class of all classes, variable of type Object can
hold reference to an object of any class and is useful to handle objects
of unknown types
Object class don’t have any data members, only member methods
116
Universal Superclass
toString ( ) // name of class @ hexadecimal code
equals( ) // compares objects
getClass( ) // final and returns object of type Class
hashCode( ) // returns hash code value for object in int
notify( ) (final)
notifyAll( ) (final)
wait( ) (final)
clone( )
finalize( )
117