0% found this document useful (0 votes)
66 views72 pages

Unit 2 Object Oriented Programming-Inheritance

Inheritance allows a class to inherit characteristics from a parent class. The child class inherits methods and data from the parent class. Inheritance creates an "is-a" relationship where the child is a more specific version of the parent. Java uses the "extends" keyword to establish inheritance between classes. Constructors are called from the topmost parent class down. The "super" keyword refers to the parent class and can be used to call parent methods or as a function in child constructors. Polymorphism in Java refers to method overloading and overriding. Overloading defines multiple methods with the same name but different parameters, while overriding replaces an inherited method with the same signature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views72 pages

Unit 2 Object Oriented Programming-Inheritance

Inheritance allows a class to inherit characteristics from a parent class. The child class inherits methods and data from the parent class. Inheritance creates an "is-a" relationship where the child is a more specific version of the parent. Java uses the "extends" keyword to establish inheritance between classes. Constructors are called from the topmost parent class down. The "super" keyword refers to the parent class and can be used to call parent methods or as a function in child constructors. Polymorphism in Java refers to method overloading and overriding. Overloading defines multiple methods with the same name but different parameters, while overriding replaces an inherited method with the same signature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 72

UNIT 2

OBJECT ORIENTED PROGRAMMING-


INHERITANCE
Inheritance
• Inheritance allows a software developer to derive a new
class from an existing one
• The existing class is called the parent class, or superclass,
or base class
• The derived class is called the child class or subclass.
• As the name implies, the child inherits characteristics of
the parent
• That is, the child class inherits the methods and data
defined for the parent class
Inheritance
• Inheritance relationships often are shown
graphically in a UML class diagram, with an
arrow with an open arrowhead pointing to the
parent class Vehicle

Car

• Inheritance should create an is-a


relationship, meaning the child is a more
specific version of the parent
Deriving Subclasses
• In Java, we use the reserved word extends
to establish an inheritance relationship

class Car extends Vehicle


{
// class contents
}
The protected Modifier
• Visibility modifiers determine which class members are
inherited and which are not
• Variables and methods declared with public visibility
are inherited; those with private visibility are not
• But public variables violate the principle of
encapsulation
• There is a third visibility modifier that helps in
inheritance situations: protected
Inheritance and Constructors

class First {
public First() { System.out.println(“ First class “); }
}
public class Second extends First {
public Second() { System.out.println(“Second class”); }
}
public class Third extends Second {
public Third() {System.out.println(“Third class”);}
}
First class
Second class
Third class

Topmost class constructor is invoked first


(like us …grandparent-->parent-->child->)
super keyword

• refers to the superclass (base class)


• usage:
– with a variable or method (most
common with a method)
– as a function inside a constructor of the
subclass
super :: with a method

class Manager extends Employee {


private double bonus;
public void setBonus(double bb) { …}
public void raise(double dd) { //overrides raise()
of Employee
super.raise(dd); // call Employee’s raise()
salary += bonus;
}
public Manager ( … ) { … }
}
super :: as a function inside a
constructor of the subclass

class Manager extends Employee {


private double bonus;
public void setBonus(double bb) { …}
public Manager ( String name, double salary, double
bonus ) {
super(name, salary);
this.bonus = bonus;
}
}
Multiple Inheritance
• Java supports single inheritance, meaning that a derived
class can have only one parent class
• Multiple inheritance allows a class to be derived from two
or more classes, inheriting the members of all parents
• Collisions, such as the same variable name in two parents,
have to be resolved
• Java does not support multiple inheritance
• In most cases, the use of interfaces gives us aspects of
multiple inheritance without the overhead
Class Hierarchies
• A child class of one parent can be the parent
of another child, forming a class hierarchy
Business

RetailBusiness ServiceBusiness

KMart Macys Kinkos


Class Hierarchies
• Two children of the same parent are called siblings
• Common features should be put as high in the
hierarchy as is reasonable
• An inherited member is passed continually down the
line
• Therefore, a child class inherits from all its ancestor
classes
• There is no single class hierarchy that is appropriate for
all situations
Polymorphism
• Polymorphism means many (poly) shapes (morph)
• In Java, polymorphism refers to the fact that you
can have multiple methods with the same name in
the same class
• There are two kinds of polymorphism:
– Overloading
• Two or more methods with different signatures
– Overriding
• Replacing an inherited method with another having the same
signature
Overloading
• class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
• static void myPrint(int i) {
System.out.println("int i = " + i);
}
• static void myPrint(double d) { // same name, different parameters
System.out.println("double d = " + d);
}
}

• int i = 5
double d = 5.0
Why overload a method?
• So you can use the same names for methods that do essentially the same
thing
– Example: println(int), println(double), println(boolean), println(String), etc.
• So you can supply defaults for the parameters:
int increment(int amount) {
count = count + amount;
return count;
}
int increment() {
return increment(1);
}
– Notice that one method can call another of the same name
• So you can supply additional information:
void printResults() {
System.out.println("total = " + total + ", average = " + average);
}
void printResult(String message) {
System.out.println(message + ": ");
printResults();
}
Overriding
• class Animal
• { • This is called
public static void main(String args[])
• {
overriding a method
Animal animal = new Animal();
Dog dog = new Dog(); • Method print in Dog
animal.print();
dog.print();
overrides method
}
void print()
print in Animal
• { • A subclass variable
System.out.println("Superclass Animal");
} can shadow a
}
• public class Dog extends Animal superclass variable,
• { but a subclass
void print()
• {
method can override
}
System.out.println("Subclass Dog");
a superclass method
}
How to override a method
• Create a method in a subclass having the same
signature as a method in a superclass
• That is, create a method in a subclass having the
same name and the same number and types of
parameters
– Parameter names don’t matter, just their types
• Restrictions:
– The return type must be the same
– The overriding method cannot be more private than the
method it overrides
Why override a method?
• Dog dog = new Dog();
System.out.println(dog);
– Prints something like Dog@feda4c00
– The println method calls the toString
method, which is defined in Java’s top-level
Object class
• Hence, every object can be printed
(though it might not look pretty)
• Java’s method public String toString()
can be overridden
Why override a method?
• If you add to class Dog the following:
public String toString() {
return name;
}
Then System.out.println(dog); will print the
dog’s name, which may be something like:
Fido
Calling an overridden method
• When your class overrides an inherited method,
it basically “hides” the inherited method
• Within this class (but not from a different class),
you can still call the overridden method, by
prefixing the call with super.
– Example: super.printEverything();
• You would most likely do this in order to observe
the DRY principle
– The superclass method will do most of the work, but
you add to it or adjust its results
– This isn’t a call to a constructor, and can occur
anywhere in your class (it doesn’t have to be first)
Overloading vs. Overriding
• Don't confuse the concepts of overloading and overriding
• Overloading deals with multiple methods with the same
name in the same class, but with different signatures
• Overriding deals with two methods, one in a parent class
and one in a child class, that have the same signature
• Overloading lets you define a similar operation in different
ways for different data
• Overriding lets you define a similar operation in different
ways for different object types
Dynamic Binding
• Binding: linking between messages and
methods

Inclusion Polymorphism + Overriding = Binding Question


Dynamic Binding
• The same entity may refer to objects of different
classes, each of which has a different implementation
of the same method
More generally, binding time is the time when an
attribute of some portion of a program, or the
meaning of a particular construct is determined
• Compile Time
• Link Time
• Execution Time:
– Program Init
– Procedure/function begin
– Statement Execution
Static vs. Dynamic Types
Employee
• Consider the call: raise_salar
Manager M; y
M.raise_salary(10); print+

• What is the type of this in the called method?


– Static Type: Employee *
• What can be determined in compile time Manager
– Dynamic Type: Manager * print++
• Actual type, as determined in run time
• No simple way for the programmer to examine the dynamic type
• Suppose that raise_salary calls print, then, which version
of print will be called?
– Based on the static type? or,
– Based on the dynamic type?
Static vs. Dynamic Types
• Static Binding: binding based on static type.
– More efficient
– Less flexible
– Static type checking leads to safer programs
• Dynamic Binding: binding based on dynamic type.
– Less efficient
– More flexible
– May need dynamic type checking!
• As it turns out, dynamic binding is the only reasonable choice:
– Why?
– If static typing is so good, why “spoil” it with dynamic binding?
final keyword
• means “constant”
• applies to
– variables (makes a var. constant), or
– methods (makes a method non-
overridable), or
– classes (makes a class non-subclassable
means “objects cannot be created”).
final keyword with a variable

class Math {

public final double pi = 3.1412;


public static double method(double x) {
double x = pi * pi;
}
}

note: variable pi is made “read-only”


final keyword with a method
class Employee {
protected String name;
protected double salary;
public final void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
then: cannot ovveride method raise() inside
the Manager class
final keyword with a class
final class Employee {
protected String name;
protected double salary;
public void raise(double dd) {
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
then: cannot create class Manager as a
subclass of class Employee (all are equal)
abstract classes

• abstract classes
– may have both implemented and non-
implemented methods
sample abstract class
abstract class TwoDimensionalGeoFigure {
public abstract double area();
public abstract double perimeter();
public abstract void printInfo();
public void setOutlineColor(Color cc) {
// code to set the color
}
public void setInsideColor(Color cc) {
// code to set the color
}
}
The Object Class
• A class called Object is defined in the java.lang
package of the Java standard class library
• All classes are derived from the Object class
• If a class is not explicitly defined to be the child of an
existing class, it is assumed to be the child of the
Object class
• Therefore, the Object class is the ultimate root of
all class hierarchies
The Object Class
• The Object class contains a few useful methods,
which are inherited by all classes
• For example, the toString method is defined in the
Object class
• Every time we have defined toString, we have
actually been overriding an existing definition
• The toString method in the Object class is defined
to return a string that contains the name of the object’s
class together along with some other information
The Object Class
• The equals method of the Object class returns true
if two references are aliases
• We can override equals in any class to define equality
in some more appropriate way
• The String class (as we've seen) defines the equals
method to return true if two String objects contain
the same characters
• Therefore the String class has overridden the
equals method inherited from Object in favor of its
own version
Reflection
• What exactly is a class?
• It’s a collection of different things, such as:
– Fields
– Methods
– Constructors

• We define these different things with names, types,


parameters, values, expressions, etc while
programming, but in reflection all of this already exists.
Programming vs Reflecting
• We use reflection to manipulate things that
already exist and, normally, are set.
• But unlike programming, we are not tied to
specific names, types or views.
• We have the ability to dynamically change what
things are, regardless of how they were written!
• More specifically, we are modifying objects at
runtime.
Uses of Reflection
• Some common uses of reflection:
– To load and use classes unknown at compile time,
but have set methods.
• Example: The Critters assignment
– Test programs by forcing specific states
– By debuggers to inspect running programs
– Malicious things
• Hacking
Programming Reflection
• To program with reflection, we must put on
our meta-thinking caps.
• We are going to modify classes from classes
with classes!
• To do this we have a great set of classes in the
following package:
– java.lang.reflect.*;
where do we start?
• To start manipulating a class we must first get a
hold of that class’s “blueprint”.
– Using the java.lang.Class class
• There are two ways to do this, if the class is
already loaded:
– Class<? extends Object> theClass = ClassName.class;

• Or if we need to cause it to load:


– Class theClass = Class.forName(“class.package”);

• We won’t use this second one, its rather complex


at times.
– Example Package: “java.lang.String”
The Parts of the Class
• Fields
• Methods
• Constructors
• Miscellaneous
Getting those sweet fields
• There are two ways to get class fields:
– getFields();
• Returns an array of Field objects, specifically all the
fields that are public for this class and its super classes.
– getDeclaredFields();
• Returns an array of Field objects, regardless of view.
• Optionally if you know the field name:
– getField(String name);
• Returns a Field with the given name
Calling all methods, report for duty
• Like Fields there are two ways to get Methods
– getMethods();
• Returns all the public methods for this class and any it
inherits from super classes.
– getDeclaredMethods();
• Returns all the methods for this class only regardless of
view.
• Like Fields you can also get a specific method,
but it takes more information.
Building blocks
• To get the constructos we have the methods:
– getConstructors()
• Returns all public constructors for the class
– getDeclaredConstructors()
• Returns all constructors for the class, regardless of view

• We can again get specific constructors with:


– getConstructor(Class<?>… parameterTypes);
• Returns the constructor that takes the given
parameters
The others
• For this session we will only focus on variables
and methods, but there are a number of other
useful methods:
– getEnclosingMethod()
• Gets the method that declared an anonymous class
– getName()
• Returns the class name
– newInstance()
• Creates a new instance of the class
Interfaces
• An interface is a way to describe what classes should
do, without specifying how they should do it.
• It’s not a class but a set of requirements for classes that
want to conform to the interface
E.g. public interface Comparable
{
int compareTo(Object
otherObject);
}
this requires that any class implementing the
Comparable interface contains a compareTo
method, and this method must take an Object
parameter and return an integer
Interface declarations
• The declaration consists of a keyword
interface, its name, and the members
• Similar to classes, interfaces can have three
types of members
– constants (fields)
– methods
– nested classes and interfaces
Interface member – constants
• An interface can define named constants, which are
public, static and final (these modifiers are
omitted by convention) automatically. Interfaces never
contain instant fields.
• All the named constants MUST be initialized
An example interface
Interface Verbose {
int SILENT = 0;
int TERSE = 1;
int NORMAL = 2;
int VERBOSE = 3;
void setVerbosity (int level);
int getVerbosity();
}
Interface member – methods
• They are implicitly abstract (omitted by
convention). So every method declaration
consists of the method header and a
semicolon.
• They are implicitly public (omitted by
convention). No other types of access
modifiers are allowed.
• They can’t be final, nor static
Modifiers of interfaces itself
• An interface can have different modifiers as
follows
– public/package(default)
– abstract
• all interfaces are implicitly abstract
• omitted by convention
To implement interfaces in a class
• Two steps to make a class implement an interface
1. declare that the class intends to implement the given
interface by using the implements keyword
class Employee implements Comparable
{ . . . }
2. supply definitions for all methods in the interface
public int compareTo(Object
otherObject) {
Employee other = (Employee)
otherObject;
if (salary < other.salary) return
-1;
if (salary > other.salary) return
1;
return 0; }
To implement interfaces in a class
• If a class leaves any method of the interface
undefined, the class becomes abstract class
and must be declared abstract
• A single class can implement multiple interfaces.
Just separate the interface names by comma
class Employee implements
Comparable, Cloneable {. . .}
Instantiation properties of interfaces
• Interfaces are not classes. You can never use the new
operator to instantiate an interface.
public interface Comparable {
. . . }
Comparable x = new Comparable( );
• You can still declare interface variables
Comparable x;
but they must refer to an object of a class that implements the
interface
class Employee implements Comparable {
. . .
}
x = new Employee( );
Object Cloning
• Recall that the “=“ operator simply copies Object
references. e.g.,
>> Student s1 = new Student(“Smith”, Jim, 3.13);
>> Student s2 = s1;
>> s1.setGPA(3.2);
>> System.out.println(s2.getGPA());
3.2
• What if we want to actually make a copy of an
Object?
• Most elegant way is to use the clone() method
inherited from Object.
Student s2 = (Student) s1.clone();
Subtleties of clone() method
• First, note that the clone method is protected
in the Object class.
• This means that it is protected for subclasses
as well.
• Hence, it cannot be called from within an
Object of another class and package.
• To use the clone method, you must override in
your subclass and upgrade visibility to public.
Steps for cloning
• To reiterate, if you would like objects of class C
to support cloning, do the following:
– implement the Cloneable interface
– override the clone method with public access
privileges
– call super.clone()
– Handle CloneNotSupported Exception.
• This will get you default cloning, but more
subtleties still lurk.
Shallow Copies
• We haven’t yet said what the default clone()
method does.
• By default, clone makes a shallow copy of all iv’s in
a class.
• Shallow copy means that all native datatype iv’s
are copied in regular way, but iv’s that are objects
are not recursed upon – that is, references are
copied.
• This is not what you typically want.
• Must override clone explicitly clone object iv’s!
Immutable Objects
• A special class of Objects are called immutable
because their state cannot be changed once set.
• Common examples are String, Integer, etc.
• Immutable object simplify programming in certain
instances, such as when writing thread safe code.
• They also simplify cloning, since an object that
cannot be changed doesn’t really need to be
deep-copied.
• See ShallowCopy2.java in course examples
Deep Copies
• For deep copies that recurse through the
object iv’s, you have to do some more work.
• super.clone() is first called to clone the first
level of iv’s.
• Returned cloned object’s object fields are then
accessed one by one and clone method is
called for each.
• See DeepClone.java example
Additional clone() properties
• Note that the following are typical, but not
strictly required:
– x.clone() != x;
– x.clone().getClass() == x.getClass();
– x.clone().equals(x);

• Finally, though no one really cares, Object


does not support clone();
Inner Classes
• Inner classes are classes defined within other
classes
– The class that includes the inner class is called the
outer class
– There is no particular location where the
definition of the inner class (or classes) must be
place within the outer class
– Placing it first or last, however, will guarantee that
it is easy to find
Inner/Outer Classes
• public class Outer
• {
• private class Inner
• {
• // inner class instance variables
• // inner class methods

• } // end of inner class definition

• // outer class instance variables


• // outer class methods
• }
Public Inner Classes
• If an inner class is marked public, then it can be used
outside of the outer class
• In the case of a nonstatic inner class, it must be created
using an object of the outer class
BankAccount account = new
BankAccount();
BankAccount.Money amount =
account.new Money("41.99");
– Note that the prefix account. must come before new
– The new object amount can now invoke methods from the
inner class, but only from the inner class
Public Inner Classes
• In the case of a static inner class, the
procedure is similar to, but simpler than, that
for nonstatic inner classes
OuterClass.InnerClass innerObject =
new
OuterClass.InnerClass();
– Note that all of the following are acceptable
innerObject.nonstaticMethod();
innerObject.staticMethod();
OuterClass.InnerClass.staticMethod();
Static Inner Classes
• A normal inner class has a connection between its
objects and the outer class object that created the inner
class object
– This allows an inner class definition to reference an instance
variable, or invoke a method of the outer class
• There are certain situations, however, when an inner
class must be static
– If an object of the inner class is created within a static method of
the outer class
– If the inner class must have static members
Static Inner Classes
• Since a static inner class has no connection to an object
of the outer class, within an inner class method
– Instance variables of the outer class cannot be referenced
– Nonstatic methods of the outer class cannot be invoked
• To invoke a static method or to name a static variable of a
static inner class within the outer class, preface each
with the name of the inner class and a dot
Inner Classes and Inheritance
• Given an OuterClass that has an InnerClass
– Any DerivedClass of OuterClass will automatically have
InnerClass as an inner class
– In this case, the DerivedClass cannot override the
InnerClass
• An outer class can be a derived class
• An inner class can be a derived class also
Anonymous Classes
• If an object is to be created, but there is no need to name the
object's class, then an anonymous class definition can be used
– The class definition is embedded inside the expression
with the new operator
– An anonymous class is an abbreviated notation for creating
a simple local object "in-line" within any expression, simply
by wrapping the desired code in a "new" expression.
• Anonymous classes are sometimes used when they are to be
assigned to a variable of another type
– The other type must be such that an object of the
anonymous class is also an object of the other type
– The other type is usually a Java interface
– Not every inner class should be anonymous, but very
simple "one-shot" local objects are such a common case
that they merit some syntactic sugar.
Anonymous Classes
Anonymous Classes
Proxy
• “The agency for another who acts through the agent;
authority to act for another” (Webster)
• “Provide a surrogate or placeholder for another
object to control access to it” (GoF)
• Types of proxies mentioned:
– remote
– “virtual” (e.g. loading on demand)
– protection
– “smart references”
• e.g. ref counting, locking, etc.
“static” proxies
implements
“real” server

uses Interface Forwards to

Client
implements Proxy

By way of
Factory

Generates or obtains
Creating a proxy
• Things you need
– A ClassLoader
– An array of interfaces to implement
– An InvocationHandler
• What’s the InvocationHandler?
– Basically, a single method. Could do anything
– Doesn’t usually implement any essential business logic
– Dispatches to an underlying service, possibly after (or before)
providing some additional service.
– Note: underlying service may itself be a proxy!
Proxy Properties
• Can be cast to any interface used in creating the proxy class.
• instanceof works as expected
• Proxy.isProxyClass() is true for the class
• Class name is undetermined, but will probably be something
like Proxy$1.
• Method invocation is encoded and dispatched to the
handler’s invoke method.
• Is Serializable
– This is huge!
– Implications for RMI, JNDI, J2EE

You might also like