Sunteți pe pagina 1din 117

CS433: Advanced Programming

Fall 2018

Lecture 3-4

FAST – NUCES 2018


Agenda
Classes & Objects

Packages & Access Modifiers

Abstract Classes & Interfaces

Inheritence & Polymorphism

FAST – NUCES 2018 2


Classes and
Objects

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).

 Identifyingthe state and behavior for real-world objects is a great way to


begin thinking in terms of object- oriented programming.

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).

 Methodsoperate on an object's internal state and serve as the primary


mechanism for object-to-object communication.

 Hidinginternal state and requiring all interaction to be performed through


an object's methods is known as data encapsulation — a fundamental
principle of object- oriented programming.

5
Advantages of using Objects?
 Modularity

 Information-hiding

 Code re-use

 Pluggability and debugging ease

6
Classes
 A class is the blueprint from which individual objects are created.

 Example

There may be thousands of other bicycles in existence, all of the same


make and model.

Each bicycle was built from the same set of blueprints and therefore
contains the same components.

In object-oriented terms, we say that your bicycle is an instance of the

class of objects known as bicycles

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

//instance variables double


xCenter; double yCenter; Sphere
double zCenter; double radius; Objects
circle
xCenter
yCenter
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

 If no object exists, no instance method can be executed

 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?

 Why main is always declared static?

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

You can have multiple initialization blocks in a class, in which case


they execute in the sequence in which they appear.

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

System.out.println(); // Start a new line


}

21
public static void main(String[] args)
{
TryInitialization example = new TryInitialization(); System.out.println("\nFirst object:");
example.listValues();

example = new TryInitialization();


System.out.println("\nSecond 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

 A constructor has two special characteristics which differentiate it from other


class methods
 A constructor always has the same name as the class
 A constructor never returns a value and you must not specify a return type even void is not
allowed

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

// Instance variables // Radius of a sphere


double radius;

double xCenter; // 3D coordinates


double yCenter; // of the center
double zCenter; // of a sphere

// Class constructor
Sphere(double theRadius, double x, double y, double z)
{

radius = theRadius; // Set the radius

// Set the coordinates of the center


xCenter = x;
yCenter = y;
zCenter = z;
++count; // Update object count
}

26
// Static method to report the number of objects created

static int getCount()

{
return count; // Return current object count

// Instance method to calculate volume

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

// Set the coordinates of the center xCenter = x;


yCenter = y;
zCenter = z;
++count; // Update object count
}

// Construct a unit sphere at a point


Sphere(double x, double y, double z)
{
xCenter = x;
yCenter = y;
zCenter = z;
radius = 1.0;
++count; // Update object count
}

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());

Sphere ball = new Sphere(4.0, 0.0, 0.0, 0.0); // Create a sphere


System.out.println("Number of objects = " + ball.getCount());

Sphere globe = new Sphere(12.0, 1.0, 1.0, 1.0); // Create a sphere


System.out.println("Number of objects = " + Sphere.getCount());

// Output the volume of each sphere System.out.println("ball volume = " +


ball.volume()); System.out.println("globe volume = " + globe.volume());
}
}

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

It is distinct from method overriding

The signature – name of method, type and order of the parameters must be
unique for each method

Return type has no effect on the signature of a method

How method overloading is useful?

 If methods do essentially the same things on different type of data

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.

It increases encapsulation.


Nested classes can lead to more readable and maintainable code.

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

 Outside.Inside inner=new Outside.Inside( );

A non-static inner class cannot have static members


A non-static nested class can access any members of the top
level class regardless of the access modifiers plus the Static
members of any static nested class within the same top level
class

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

Co-package classes enjoy special access to each other members


You don’t have to import those classes

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;

p1 public class Circle { }

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.*

Classes in your current default package

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;

public class Rectangle{ . . . } class Helper{ . . . }

then the compiled files will be located at:

<path to the parent directory of the output


files>\com\example\graphics\Rectangle.class
<path to the parent directory of the output files>\com\example\graphics\Helper.class
51
Managing Packages
Like the .java source files, the compiled .class files should be in a series
of directories that reflect the package name. However, the path to the
.class files does not have to be the same as the path to the .java source
files. You can arrange your source and class directories separately, as:

<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

The full path to the classes directory, <path_two>\classes, is called the


class path, and is set with the CLASSPATH system variable

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)

Access Modifiers are


 public
 protected
 private

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

Public Protected Default Private

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

Final variable may not be modified once it has been assigned a


value
Same as const in C++
Java.lang.Math has final variable of type double called PI
If the final variable is a reference to an object , it is the reference
that must stay the same, not the object
A final method may not be overridden

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

Public yes yes yes no

Protected no yes yes no

Default yes yes yes yes

Private no yes yes no

Static yes (inner) yes yes yes

Final yes yes yes no

Abstract yes no yes no

Native no no yes no

Synchronized no no yes yes(inside method)

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

public class TryConversions implements Conversions {

public double wattsToHP (double watts) {


return watts*WATT_TO_HP;
}

public double hpToWatts (double hp) {


return hp*HP_TO_WATT;
}

public double ouncesToGrams(double ounces) {


return ounces*OUNCE_TO_GRAM;
}

public double poundsToGrams(double pounds) {


return pounds*POUND_TO_GRAM;
}

public double inchesToMillimeters(double inches) {


return inches*INCH_TO_MM;
}

74
Example: Interface Implementation
public static void main(String args[]) {
int myWeightInPounds = 180;
int myHeightInInches = 75;

TryConversions converter = new TryConversions();


System.out.println("My weight in pounds: "
+ myWeightInPounds + " \t-in grams: "+
(int)converter.poundsToGrams(myWeightInPounds));
System.out.println("My height in inches: " + myHeightInInches t-in millimeters: “ +
(int)converter.inchesToMillimeters(myHeightInInches));
}
} 75
Interfaces
Every method declared in the interface should have a definition within
the class if you are going to create objects of the class
Since methods in an interface are public by default you must use the
public keyword when you define them in your class, otherwise your code
wont compile. Why?
You can implement as many number of interfaces as you like in your
class
public class MyClass implements MyInterface,OneIntface

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

Base interface is also called super interface

An interface can use the contents of several other interfaces

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

 public interface MyInterface extends OneIntface, TwoInface

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);
}

public interface DoItPlus extends DoIt { boolean


didItWork(int i, double x, String s);
}
Using Interfaces
Interfaces vs Inheritance?

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 {

// this (object calling isLargerThan) and


// other must be instances of the same class
// returns 1, 0, -1 if this is greater
// than, equal to, or less than other

public int isLargerThan(Relatable other);


}

81
Example: Interface as Type
public Object findLargest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;


Relatable obj2 = (Relatable)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.

When to use abstract methods in Java?


A class must be declared abstract when it has one or more abstract methods. A
method is declared abstract when it has a method heading, but no body – which
means that an abstract method has no implementation code inside curly braces
like normal methods do.

Why you would want to declare a method as abstract is best illustrated by


an example. Take a look at the code below:

83
/* the Figure class must be declared as abstract because it contains an abstract method */

public abstract class Figure


{
/* because this is an abstract method the body will be blank */
public abstract float getArea();
}

public class Circle extends Figure


{
private float radius;

public float getArea()


{
return (3.14 * (radius * 2));
}
}

public class Rectangle extends Figure


{
private float length, width;

public float getArea(Figure other)


{
return length * width;
}
}

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.

A non abstract class is called a concrete class


You should also know that any non abstract class is called a concrete class. Knowing your
terminology defintely pays off in an interview.

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.

Any class that implements an interface must satisfy 2 conditions:

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.

This is what an interface called "Dog" would look like:

public interface Dog


{
public boolean Barks();

public boolean isGoldenRetriever();


}
Now, if a class were to implement this interface, this is what it would look like:

public class SomeClass implements Dog


{
public boolean Barks{
// method definition here

87
}

public boolean isGoldenRetriever{


// method definition here
}
}

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:

Abstract classes and inheritance


1.Abstract classes are meant to be inherited from, and when one class inherits from another it means that there is a strong relationship between the 2
classes. For instance, if we have an abstract base class called "Canine", any deriving class should be an animal that belongs to the Canine family
(like a Dog or a Wolf). The reason we use the word "should" is because it is up to the
Java developer to ensure that relationship is maintained.

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.

Interfaces are a good substitute for multiple inheritance


2.Java does not allow multiple inheritance – see the discussion onJava Multiple Inheritance if you need a refresher on this. In Java, a class can only
derive from one class, whether it’s abstract or not. However, a class can implement multiple interfaces – which could be considered as an alternative
to for multiple inheritance. So, one major difference is that a Java class can inherit
from only one abstract class, but can implement multiple interfaces.

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.

When to use abstract class and interface in Java

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);
}

public String toString()


{
return "This is a " + type;
}

private String type;


}

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?

 When you define your own constructor in a class, no default constructor


is created by the compiler. Thus you have to define the no argument
constructor for the class yourself so that in a derived class you don’t get
the compile error due to call to default constructor of base class

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;
}

private String name; // Name of a Dog


private String breed; // Dog 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);
}

public String toString()


{
return "This is a " + type;
}

// Dummy method to be implemented in the derived classes


public void sound()
{
}

private String type;


}
108
Example – Polymorphism
public class Cat extends Animal
{
public Cat(String aName)
{
super("Cat"); // Call the base constructor
name = aName; // Supplied name
breed = "Unknown"; // Default breed value
}

public Cat(String aName, String aBreed)


{
super("Cat"); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}

109
Example – Polymorphism
// Return a String full of a cat's details

public String toString()


{
return super.toString() + "\nIt's " + name + " the " + breed;
}

// A miaowing method
public void sound()
{
System.out.println("Miiaooww");
}

private String name; // Name of a cat


private String breed; // Cat breed
}

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

A variable of base type can store a reference to an object of any derived


type, the kind of object stored is not known until the program executes.
Thus the choice of which method to execute has to be made dynamically
when the program is running

Your program can adapt at runtime to accommodate and process


different kinds of data quite automatically

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

S-ar putea să vă placă și