0% found this document useful (0 votes)
3 views129 pages

Module 03

The document covers Object Oriented Programming concepts, focusing on inheritance, method overriding, and the use of the super() function in Java. It explains the structure and behavior of classes and subclasses, including memory allocation for multidimensional arrays and the execution order of constructors. Additionally, it discusses abstract classes, final methods, and dynamic method dispatch, emphasizing the importance of polymorphism in object-oriented programming.

Uploaded by

f20240032
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views129 pages

Module 03

The document covers Object Oriented Programming concepts, focusing on inheritance, method overriding, and the use of the super() function in Java. It explains the structure and behavior of classes and subclasses, including memory allocation for multidimensional arrays and the execution order of constructors. Additionally, it discusses abstract classes, final methods, and dynamic method dispatch, emphasizing the importance of polymorphism in object-oriented programming.

Uploaded by

f20240032
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming

Dr. Tanmaya Mahapatra


BITS Pilani Department of Computer Science and Information Systems
Pilani Campus
Contents

• Inheritance Basics with Examples


• Inheritance and Private Members
• References
• Super () Usages
• Multi-level Inheritance Example
• Calling of Constructors
• Method Overriding

CS F213 Object Oriented Programming 2


BITS Pilani, Pilani Campus
Multidimensional Arrays

• When we allocate memory for a multidimensional array, we


need to specify the memory for the first dimension only.
• We can allocate the remaining dimensions separately:

int twoD[][] = new int[4][];


twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

CS F213 Object Oriented Programming 3


BITS Pilani, Pilani Campus
CS F213 Object Oriented Programming 4
BITS Pilani, Pilani Campus
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
Inheritance

• Inheritance is one of the cornerstones of object-oriented


programming because it allows the creation of hierarchical
classifications.
• Using inheritance -- we can create a general class that defines
traits common to a set of related items.
– This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
• In the terminology of Java, a class that is inherited is called a
superclass.
• The class that does the inheriting is called a subclass.

CS F213 Object Oriented Programming 7


BITS Pilani, Pilani Campus
Inheritance

• A subclass is a specialized version of a superclass.


• It inherits all of the members defined by the superclass and
adds its own, unique elements.
• The general form of a class declaration that inherits a
superclass is :
class subclass-name extends superclass-name {
// body of class
}
Demo → 2 Examples Box, Boxweight and
DemoBoxweight
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
Inheritance: Important Points

1. We can only specify one superclass for any subclass that we


create. Java does not support the inheritance of multiple
superclasses into a single subclass.
2. We can create a hierarchy of inheritance in which a subclass
becomes a superclass of another subclass.
3. No class can be a superclass of itself.
• A subclass includes all of the members of its superclass -- it
cannot access those members of the superclass that have
been declared as private (Code PrivateInhritance). A class
member that has been declared as private will remain
private to its class. It is not accessible by any code outside its
class, including subclasses.
CS F213 Object Oriented Programming 9
BITS Pilani, Pilani Campus
Inheritance

• A reference variable of a superclass can be assigned a


reference to any subclass derived from that superclass.
(Code Example) RefDemo
• It is important to understand that it is the type of the
reference variable—not the type of the object that it refers
to—that determines what members can be accessed.
• When a reference to a subclass object is assigned to a
superclass reference variable, we can access only those parts
of the object defined by the superclass.
• This is why plainbox can’t access weight even when it refers
to a BoxWeight object.

CS F213 Object Oriented Programming 10


BITS Pilani, Pilani Campus
Super() to call constructors

• A subclass can call a constructor defined by its superclass by


use of the following form of super:
– super(arg-list);
• arg-list specifies any arguments needed by the constructor in
the superclass.
• super( ) must always be the first statement executed inside a
subclass’ constructor.

CS F213 Object Oriented Programming 11


BITS Pilani, Pilani Campus
Super() to call constructors

CS F213 Object Oriented Programming 12


BITS Pilani, Pilani Campus
Super() to call constructors

• Here, BoxWeight( ) calls super( ) with the arguments w, h,


and d.
• This causes the Box constructor to be called, which initializes
width, height, and depth using these values.
• BoxWeight no longer initializes these values itself.
• It only needs to initialize the value unique to it: weight. This
leaves Box free to make these values private if desired.
• Since constructors can be overloaded, super( ) can be called
using any form defined by the superclass.
• The constructor executed will be the one that matches the
arguments. (Code Example) Boxweight DemoBoxweight
CS F213 Object Oriented Programming 13
BITS Pilani, Pilani Campus
Super() to call constructors

• super( ) is passed an object of type BoxWeight—not of type Box. This still


invokes the constructor Box(Box ob).
• A superclass variable can be used to reference any object derived from
that class. We are able to pass a BoxWeight object to the Box constructor.
Box only has knowledge of its own members. Code→ DemoSuper

CS F213 Object Oriented Programming 14


BITS Pilani, Pilani Campus
Super() to call constructors

1. When a subclass calls super(), it is calling the constructor of


its immediate superclass.
2. Thus, super( ) always refers to the superclass immediately
above the calling class. This is true even in a multileveled
hierarchy.
3. super( ) must always be the first statement executed inside a
subclass constructor.

CS F213 Object Oriented Programming 15


BITS Pilani, Pilani Campus
Second usage of super

• The second form of super acts somewhat like this,


except that it always refers to the superclass of the
subclass in which it is used.
– [Link]
• Here, member can be either a method or an instance
variable.
• This second form of super is most applicable to
situations in which member names of a subclass hide
members by the same name in the superclass. (code
demo) (UseSuper)
CS F213 Object Oriented Programming 16
BITS Pilani, Pilani Campus
Multi-level Hierarchy

• Code Example→ Shipment & DemoShipment.


• The subclass BoxWeight is used as a superclass to create the
subclass called Shipment.
• Shipment inherits all of the traits of BoxWeight and Box, and
adds a field called cost, which holds the cost of shipping such
a parcel.

CS F213 Object Oriented Programming 17


BITS Pilani, Pilani Campus
Multi-level Hierarchy

1. super( ) always refers to the constructor in the closest


superclass.
2. The super( ) in Shipment calls the constructor in BoxWeight.
3. The super( ) in BoxWeight calls the constructor in Box.
4. In a class hierarchy, if a superclass constructor requires
arguments, then all subclasses must pass those arguments
“up the line.”
5. This is true whether or not a subclass needs arguments of its
own.

CS F213 Object Oriented Programming 18


BITS Pilani, Pilani Campus
When are Constructors executed?

• When a class hierarchy is created, in what order are the constructors for
the classes that make up the hierarchy executed? For example, given a
subclass called B and a superclass called A, is A’s constructor executed
before B’s, or vice versa?
• The answer is that in a class hierarchy, constructors complete their
execution in order of derivation, from superclass to subclass. Further,
since super( ) must be the first statement executed in a subclass’
constructor, this order is the same whether or not super( ) is used.
• If super( ) is not used, then the default or parameterless constructor of
each superclass will be executed.
• Demo → CallingCons & Test1 and Test2 with no default demo

CS F213 Object Oriented Programming 19


BITS Pilani, Pilani Campus
When are Constructors executed?

• the constructors are executed in order of derivation.


• It makes sense that constructors complete their execution in
order of derivation.
• Because a superclass has no knowledge of any subclass, any
initialization it needs to perform is separate from and possibly
prerequisite to any initialization performed by the subclass.
Therefore, it must complete its execution first.

CS F213 Object Oriented Programming 20


BITS Pilani, Pilani Campus
Method Overriding

• In a class hierarchy, when a method in a subclass has the same


name and type signature as a method in its superclass, then
the method in the subclass is said to override the method in
the superclass.
• When an overridden method is called from within its subclass,
it will always refer to the version of that method defined by
the subclass.
• The version of the method defined by the superclass will be
hidden.
• Demo → Override

CS F213 Object Oriented Programming 21


BITS Pilani, Pilani Campus
Method Overriding

• Method overriding occurs only when the names and the type
signatures of the two methods are identical.
• If they are not, then the two methods are simply overloaded.
• Demo – [Link]

CS F213 Object Oriented Programming 22


BITS Pilani, Pilani Campus
What has been covered?

• Inheritance Basics with Examples ✔


• Inheritance and Private Members ✔
• References ✔
• Super () Usages ✔
• Multi-level Inheritance Example ✔
• Calling of Constructors ✔
• Method Overriding ✔

CS F213 Object Oriented Programming 23


BITS Pilani, Pilani Campus
Object Oriented Programming

BITS Pilani Dr. Tanmaya Mahapatra


Pilani Campus Department of Computer Science and Information Systems
Contents

• Method Overriding
• Dynamic Method Dispatch
• Abstract Classes
• Final and Inheritance

CS F213 Object Oriented Programming 2


BITS Pilani, Pilani Campus
Method Overriding

• In a class hierarchy, when a method in a subclass has the same


name and type signature as a method in its superclass, then
the method in the subclass is said to override the method in
the superclass.
• When an overridden method is called from within its subclass,
it will always refer to the version of that method defined by
the subclass.
• The version of the method defined by the superclass will be
hidden.
• Demo → Override

CS F213 Object Oriented Programming 3


BITS Pilani, Pilani Campus
Method Overloading

• Method overriding occurs only when the names and the type
signatures of the two methods are identical.
• If they are not, then the two methods are simply overloaded.
• Demo → [Link]

CS F213 Object Oriented Programming 4


BITS Pilani, Pilani Campus
Dynamic Method Dispatch

• Dynamic method dispatch is the mechanism by which a call to an


overridden method is resolved at run time, rather than compile
time.
• Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
• A superclass reference variable can refer to a subclass object.
• Java uses this fact to resolve calls to overridden methods at run
time.
• When an overridden method is called through a superclass
reference, Java determines which version of that method to execute
based upon the type of the object being referred to at the time the
call occurs.
• This determination is made at run time. When different types of
objects are referred to, different versions of an overridden method
will be called.
CS F213 Object Oriented Programming 5
BITS Pilani, Pilani Campus
Dynamic Method Dispatch

• It is the type of the object being referred to (not the type of


the reference variable) that determines which version of an
overridden method will be executed.
• If a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to
through a superclass reference variable, different versions of
the method are executed.
• Demo → [Link]

CS F213 Object Oriented Programming 6


BITS Pilani, Pilani Campus
Dynamic Method Dispatch

• Overridden methods allow Java to support run-time


polymorphism.
• Polymorphism is essential to object-oriented programming for
one reason: it allows a general class to specify methods that
will be common to all of its derivatives, while allowing
subclasses to define the specific implementation of some or
all of those methods.
• Overridden methods are another way that Java implements
the “one interface, multiple methods” aspect of
polymorphism.
• Demo → [Link]

CS F213 Object Oriented Programming 7


BITS Pilani, Pilani Campus
Abstract Classes

• There are situations in which we would want to define a superclass that


declares the structure of a given abstraction without providing a complete
implementation of every method.
• Sometimes we need to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass
to fill in the details.
• Such a class determines the nature of the methods that the subclasses
must implement.
• One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
• This is the case with the class Figure. The definition of area( ) is simply a
placeholder. It will not compute and display the area of any type of object.

CS F213 Object Oriented Programming 8


BITS Pilani, Pilani Campus
Abstract Classes

• We can make sure that certain methods be overridden by


subclasses by specifying the abstract type modifier.
• These methods are sometimes referred to as subclasser
responsibility because they have no implementation specified
in the superclass.
• Thus, a subclass must override them—it cannot simply use
the version defined in the superclass.
• To declare an abstract method, use this general form:
– abstract type name(parameter-list);
• no method body is present.

CS F213 Object Oriented Programming 9


BITS Pilani, Pilani Campus
Abstract Classes

• Any class that contains one or more abstract methods must also be
declared abstract.
• To declare a class abstract, we use the abstract keyword in front of the
class keyword at the beginning of the class declaration.
• There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator.
• Such objects would be useless, because an abstract class is not fully
defined.
• We cannot declare abstract constructors, or abstract static methods.
• Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be declared abstract itself.
• Demo → AbstractDemo, AbstractAreas

CS F213 Object Oriented Programming 10


BITS Pilani, Pilani Campus
Final

• The keyword final has three uses.


• It can be used to create the equivalent of a named constant.
• While method overriding is one of Java’s most powerful
features, there will be times when you will want to prevent it
from occurring.
• To disallow a method from being overridden, specify final as a
modifier at the start of its declaration.
• Methods declared as final cannot be overridden

CS F213 Object Oriented Programming 11


BITS Pilani, Pilani Campus
Final and Inheritance

Because meth( ) is declared as final, it cannot be overridden in


B. If you attempt to do so, a compile-time error will result.

CS F213 Object Oriented Programming 12


BITS Pilani, Pilani Campus
Final

• Java resolves calls to methods dynamically, at run time. This is


called late binding.
• However, since final methods cannot be overridden, a call to
one can be resolved at compile time. This is called early
binding.
• When a small final method is called, often the Java compiler
can copy the bytecode for the subroutine directly inline with
the compiled code of the calling method, thus eliminating the
costly overhead associated with a method call.

CS F213 Object Oriented Programming 13


BITS Pilani, Pilani Campus
Final

• Sometimes we want to prevent a class from being inherited.


• To do this precede the class declaration with final.
• Declaring a class as final implicitly declares all of its methods
as final, too.
• It is illegal to declare a class as both abstract and final since
an abstract class is incomplete by itself and relies upon its
subclasses to provide complete implementations.

CS F213 Object Oriented Programming 14


BITS Pilani, Pilani Campus
Final

CS F213 Object Oriented Programming 15


BITS Pilani, Pilani Campus
What has been covered?

• Method Overriding ✔
• Dynamic Method Dispatch ✔
• Abstract Classes ✔
• Final and Inheritance ✔

CS F213 Object Oriented Programming 16


BITS Pilani, Pilani Campus
Object Oriented Programming

BITS Pilani Dr. Tanmaya Mahapatra


Pilani Campus Department of Computer Science and Information Systems
Contents

• Interfaces
• Interfaces Vs Abstract Classes

CS F213 Object Oriented Programming 2


BITS Pilani, Pilani Campus
Interfaces

• Using the keyword interface, we can fully abstract a class’


interface from its implementation.
• Using interface, we can specify what a class must do, but not
how it does it.
• Interfaces are syntactically similar to classes, but they lack
instance variables, and, as a general rule, their methods are
declared without any body.
• Once it is defined, any number of classes can implement an
interface.
• One class can implement any number of interfaces.

CS F213 Object Oriented Programming 3


BITS Pilani, Pilani Campus
Interfaces

CS F213 Object Oriented Programming 4


BITS Pilani, Pilani Campus
Interfaces

• When no access modifier is included, then default access


results, and the interface is only available to other members
of the package in which it is declared.
• When it is declared as public, the interface can be used by
code outside its package.
• The interface must be the only public interface declared in the
file and the file must have the same name as the interface.

CS F213 Object Oriented Programming 5


BITS Pilani, Pilani Campus
Interfaces

• name is the name of the interface, and can be any valid


identifier.
1. The methods that are declared have no bodies.
2. They end with a semicolon after the parameter list.
3. They are, essentially, abstract methods.
4. Each class that includes such an interface must implement
all of the methods.

CS F213 Object Oriented Programming 6


BITS Pilani, Pilani Campus
Interfaces

• Prior to JDK 8, an interface could not define any


implementation.
• Prior to JDK 8, an interface could define only “what,” but not
“how.”
• Beginning with JDK 8, it is possible to add a default
implementation to an interface method.
• JDK 8 also added static interface methods.
• With JDK 9, an interface can include private methods.
• It is now possible for interface to specify some behavior.

CS F213 Object Oriented Programming 7


BITS Pilani, Pilani Campus
Interfaces

1. Variables can be declared inside interface declarations.


2. They are implicitly final and static, meaning they cannot be
changed by the implementing class.
3. They must also be initialized.
4. All methods and variables are implicitly public

CS F213 Object Oriented Programming 8


BITS Pilani, Pilani Campus
Interfaces

• Example of an interface definition. It declares a simple


interface that contains one method called callback( ) that
takes a single integer parameter.

CS F213 Object Oriented Programming 9


BITS Pilani, Pilani Campus
Implementing an Interface

• To implement an interface, include the implements clause in a


class definition, and then create the methods required by the
interface.
• The general form of a class that includes the implements
clause looks like this:

CS F213 Object Oriented Programming 10


BITS Pilani, Pilani Campus
Implementing an Interface

1. If a class implements more than one interface, the interfaces


are separated with a comma.
2. If a class implements two interfaces that declare the same
method, then the same method will be used by clients of
either interface.
3. The methods that implement an interface must be declared
public.
4. The type signature of the implementing method must match
exactly the type signature specified in the interface
definition.

CS F213 Object Oriented Programming 11


BITS Pilani, Pilani Campus
Implementing an Interface

When we implement an interface method, it must be declared as


public.

CS F213 Object Oriented Programming 12


BITS Pilani, Pilani Campus
Implementing an Interface

• It is both permissible and common for classes that implement


interfaces to define additional members of their own.

CS F213 Object Oriented Programming 13


BITS Pilani, Pilani Campus
Accessing Implementations
Through Interface References

1. We can declare variables as object references that use an


interface rather than a class type.
2. Any instance of any class that implements the declared
interface can be referred to by such a variable.
• When we call a method through one of these references, the
correct version will be called based on the actual instance of
the interface being referred to.
• The method to be executed is looked up dynamically at run
time.
• Demo → Callback, Client, AnotherClient, InterfaceReference,
InterfaceReference2, Camel
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
Accessing Implementations
Through Interface References

CS F213 Object Oriented Programming 15


BITS Pilani, Pilani Campus
Partial Implementations

• If a class includes an interface but does not fully implement


the methods required by that interface, then that class must
be declared as abstract.

• The class Incomplete does not implement callback( ) and


must be declared as abstract. Any class that inherits
Incomplete must implement callback( ) or be declared
abstract itself.
CS F213 Object Oriented Programming 16
BITS Pilani, Pilani Campus
Nested Interfaces

• An interface can be declared a member of a class or another


interface.
• Such an interface is called a member interface or a nested
interface.
• A nested interface can be declared as public, private, or
protected.
• This differs from a top-level interface, which must either be
declared as public or use the default access level.
• When a nested interface is used outside of its enclosing
scope, it must be qualified by the name of the class or
interface of which it is a member.
• Demo → [Link]
CS F213 Object Oriented Programming 17
BITS Pilani, Pilani Campus
Variables in Interfaces

• We can use interfaces to import shared constants into


multiple classes by simply declaring an interface that contains
variables that are initialized to the desired values.
• When we include that interface in a class (that is, when we
“implement” the interface), all of those variable names will be
in scope as constants.
• If an interface contains no methods, then any class that
includes such an interface doesn’t actually implement
anything.
• It is as if that class were importing the constant fields into the
class name space as final variables.
• Demo → [Link]

CS F213 Object Oriented Programming 18


BITS Pilani, Pilani Campus
Extending Interfaces

• One interface can inherit another by use of the keyword


extends.
• The syntax is the same as for inheriting classes.
• When a class implements an interface that inherits another
interface, it must provide implementations for all methods
required by the interface inheritance chain.
• Demo → [Link]

CS F213 Object Oriented Programming 19


BITS Pilani, Pilani Campus
Default Methods in Interfaces

• A default method provides a default implementation for an


interface method.
• By use of a default method, it is possible for an interface
method to provide a body, rather than being abstract.
• The default method is also referred to as an extension
method.
• A primary motivation for the default method was to provide a
means by which interfaces could be expanded without
breaking existing code.
• Demo → [Link]

CS F213 Object Oriented Programming 20


BITS Pilani, Pilani Campus
Default Methods in Interfaces

• It is important to point out that the addition of default


methods does not change a key aspect of interface: its
inability to maintain state information.
• An interface still cannot have instance variables, for example.
• The defining difference between an interface and a class is
that a class can maintain state information, but an interface
cannot.

CS F213 Object Oriented Programming 21


BITS Pilani, Pilani Campus
Multiple Inheritance Issues

• Java does not support the multiple inheritance of classes.


• Now that an interface can include default methods, can we use an
interface to provide a way around this restriction?
• No.
• Default methods do offer a bit of what one would normally
associate with the concept of multiple inheritance
• For example, we might have a class that implements two interfaces.
• If each of these interfaces provides default methods, then some
behavior is inherited from both.
• To a limited extent, default methods do support multiple
inheritance of behavior. In such a situation, it is possible that a
name conflict will occur.
CS F213 Object Oriented Programming 22
BITS Pilani, Pilani Campus
Issues

• Scenario: Assume that two interfaces called Alpha and Beta


are implemented by a class called MyClass.
– What happens if both Alpha and Beta provide a method called reset( )
for which both declare a default implementation?
– Is the version by Alpha or the version by Beta used by MyClass?
– Consider a situation in which Beta extends Alpha.
– Which version of the default method is used?
– Or, what if MyClass provides its own implementation of the method?
• To handle these and other similar types of situations, Java
defines a set of rules that resolves such conflicts.

CS F213 Object Oriented Programming 23


BITS Pilani, Pilani Campus
Rules

• Rule 1: a class implementation takes priority over an interface


default implementation. Thus, if MyClass provides an override
of the reset( ) default method, MyClass’ version is used. This
is the case even if MyClass implements both Alpha and Beta.
In this case, both defaults are overridden by MyClass’
implementation.
• Rule 2: In cases in which a class implements two interfaces
that both have the same default method, but the class does
not override that method, then an error will result.
– if MyClass implements both Alpha and Beta, but does not override
reset( ), then an error will occur.

CS F213 Object Oriented Programming 24


BITS Pilani, Pilani Campus
Rules

• In cases in which one interface inherits another, with both


defining a common default method, the inheriting interface’s
version of the method takes precedence.
• If Beta extends Alpha, then Beta’s version of reset( ) will be
used.
• It is possible to explicitly refer to a default implementation in
an inherited interface by using this form of super.
– [Link]( )
• If Beta wants to refer to Alpha’s default for reset( ), it can use
this statement:
– [Link]();

CS F213 Object Oriented Programming 25


BITS Pilani, Pilani Campus
Use Static Methods in an Interface

• We can define one or more static methods.


• Like static methods in a class, a static method defined by an
interface can be called independently of any object.
• NO implementation of the interface is necessary, and no
instance of the interface is required, in order to call a static
method.
• [Link]

CS F213 Object Oriented Programming 26


BITS Pilani, Pilani Campus
Use Static Methods in an Interface

static interface methods are not


inherited by either an
implementing class or a
subinterface.

The getDefaultNumber( ) method can be called, as


int defNum = [Link]();

CS F213 Object Oriented Programming 27


BITS Pilani, Pilani Campus
Private Interface Methods

• Beginning with JDK 9, an interface can include a private method.


1. A private interface method can be called only by a default method
or another private method defined by the same interface.
2. Because a private interface method is specified private, it cannot
be used by code outside the interface in which it is defined.
3. This restriction includes sub-interfaces because a private interface
method is not inherited by a sub-interface.
• The key benefit of a private interface method is that it lets two or
more default methods use a common piece of code, thus avoiding
code duplication

CS F213 Object Oriented Programming 28


BITS Pilani, Pilani Campus
Which one to use?

• Use abstract class and inheritance if you can


make the statement “A is a B”.
• Use interfaces if you can make the statement
“A is capable of [doing] as”,
• Abstract for what a class is, interface for what
a class can do.

CS F213 Object Oriented Programming 29


BITS Pilani, Pilani Campus
Interfaces Vs Abstract Classes

• Abstract classes can have non-abstract methods that


have method definitions. This gets inherited.
• Interfaces do not allow any method definitions.
▪ Abstract classes can have constructors. This may
seem a little silly because we can't construct objects
from an abstract class. However, when we write child
classes, it calls the constructor of the parent class,
even if the parent class is abstract.
▪ Interfaces can't have constructors.
[Link]
CS F213 Object Oriented Programming 30
BITS Pilani, Pilani Campus
Interfaces Vs Abstract Classes

1. Abstract classes can have private methods. Interfaces can't.


2. Abstract classes can have instance variables (these are
inherited by child classes). Interfaces can’t.
3. A concrete class can only extend one class (abstract or
otherwise). However, a concrete class can implement many
interfaces. This fact has nothing to do with abstract classes. A
class can only have one parent class (although the parent
class can have a parent class, and its parent can have a
parent class, and so forth), regardless of whether the class is
abstract or not.

CS F213 Object Oriented Programming 31


BITS Pilani, Pilani Campus
What has been covered?

• Interfaces✔
• Interfaces Vs Abstract Classes ✔

CS F213 Object Oriented Programming 32


BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Object-Oriented Programming

Packages: Putting Classes Together


Introduction
• The main feature of OOP is its ability to support the reuse of
code:
– Extending the classes (via inheritance)
– Implementing the interfaces (will be discussed in the next class)
• The features in basic form limited to reusing the classes
within a program.
• What if we need to use classes from other programs without
physically copying them into the program under
development ?
• In Java, this is achieved by using what is known as
“packages”, a concept similar to “class libraries” in other
languages.

2
BITS Pilani, Pilani Campus
Packages

• Packages are Java’s way of grouping a number of related


classes and/or interfaces together into a single unit. That
means, packages act as “containers” for classes.
• The benefits of organising classes into packages are:
– The classes contained in the packages of other programs/applications
can be reused.
– In packages classes can be unique compared with classes in other
packages. That two classes in two different packages can have the
same name. If there is a naming clash, then classes can be accessed
with their fully qualified name.
– Classes in packages can be hidden if we don’t want other packages to
access them.
– Packages also provide a way for separating “design” from coding.

3
BITS Pilani, Pilani Campus
Java Foundation Packages

• Java provides a large number of classes groped into different packages


based on their functionality.
• The six foundation Java packages are:
– [Link]
• Contains classes for primitive types, strings, math functions, threads, and exception
– [Link]
• Contains classes such as vectors, hash tables, date etc.
– [Link]
• Stream classes for I/O
– [Link]
• Classes for implementing GUI – windows, buttons, menus etc.
– [Link]
• Classes for networking
– [Link]
• Classes for creating and implementing applets

4
BITS Pilani, Pilani Campus
Using System Packages

• The packages are organised in a hierarchical structure. For


example, a package named “java” contains the package “awt”,
which in turn contains various classes required for
implementing GUI (graphical user interface).
java
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt
Graphics awt Package containing
Font classes

Image Classes containing


… methods
5
BITS Pilani, Pilani Campus
Accessing Classes from Packages

• There are two ways of accessing the classes stored in packages:


– Using fully qualified class name
• [Link](x);
– Import package and use class name directly.
• import [Link]
• [Link](x);
• Selected or all classes in packages can be imported:

import [Link];
import package.*;

• Implicit in all programs: import [Link].*;


• package statement(s) must appear first

6
BITS Pilani, Pilani Campus
Creating Packages

• Java supports a keyword called “package” for creating user-


defined packages. The package statement must be the first
statement in a Java source file (except comments and white
spaces) followed by one or more classes.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
• Package name is “myPackage” and classes are considred as
part of this package; The code is saved in a file called
“[Link]” and located in a directory called “myPackage”.

7
BITS Pilani, Pilani Campus
Creating Sub Packages

• Classes in one or more source files can be part of the same


packages.
• As packages in Java are organised hierarchically, sub-
packages can be created as follows:
– package [Link]
– package [Link]
• Store “thirdPackage” in a subdirectory named
“myPackage\secondPackage”. Store “secondPackage” and
“Math” class in a subdirectory “myPackage”.

8
BITS Pilani, Pilani Campus
Accessing a Package

• As indicated earlier, classes in packages can be


accessed using a fully qualified name or using a
short-cut as long as we import a corresponding
package.
• The general form of importing package is:
– import package1[.package2][…].classname
– Example:
• import [Link];
• import [Link]
– All classes/packages from higher-level package can be
imported as follows:
• import myPackage.*;

9
BITS Pilani, Pilani Campus
Using a Package

• Let us store the code listing below in a file named


“[Link]” within subdirectory named “myPackage” within
the current directory (say “abc”).
package myPackage;
public class ClassA {
// class body
public void display(){
[Link]("Hello, I am ClassA");
}
}
class ClassB {
// class body
}

10
BITS Pilani, Pilani Campus
Using a Package

• Within the current directory (“abc”) store the


following code in a file named “[Link]”
import [Link];
public class ClassX{
public static void main(String args[]){
ClassA objA = new ClassA();
[Link]();
}
}

11
BITS Pilani, Pilani Campus
Compiling and Running

• When [Link] is compiled, the compiler compiles


it and places .class file in current directly. If .class of
ClassA in subdirectory “myPackage” is not found, it
compiles ClassA also.
• Note: It does not include code of ClassA into ClassX
• When the program ClassX is run, java loader looks for
[Link] file in a package called “myPackage” and
loads it.

12
BITS Pilani, Pilani Campus
Using a Package

• Let us store the code listing below in a file named


“[Link]” within subdirectory named “secondPackage”
within the current directory (say “abc”).
package secondPackage;
public class ClassC {
// class body
public void display(){
[Link]("Hello, I am ClassC");
}
}

13
BITS Pilani, Pilani Campus
Using a Package

• Within the current directory (“abc”) store the


following code in a file named “[Link]”
import [Link];
import [Link];
public class ClassY{
public static void main(String args[]){
ClassA objA = new ClassA();
ClassC objC = new ClassC();
[Link]();
[Link]();
}
}

14
BITS Pilani, Pilani Campus
Protection and Packages

• All classes (or interfaces) accessible to all others in


the same package.
• Class declared public in one package is accessible
within another. Non-public class is not
• Members of a class are accessible from a difference
class, as long as they are not private
• protected members of a class in a package are
accessible to subclasses in a different class

15
BITS Pilani, Pilani Campus
Visibility - Revisited

• Public keyword applied to a class, makes it


available/visible everywhere. Applied to a method or
variable, completely visible.
• Private fields or methods for a class only visible
within that class. Private members are not visible
within subclasses, and are not inherited.
• Protected members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.

16
BITS Pilani, Pilani Campus
Visibility Modifiers

Accessible to: public protected Package private


(default)

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass in Yes Yes No No


different package

Non-subclass Yes No No No
different package

17
BITS Pilani, Pilani Campus
Adding a Class to a Package

• Consider an existing package that contains a class


called “Teacher”:
package pack1;
public class Teacher{
// class body
}

• This class is stored in “[Link]” file within a


directory called “pack1”.
• How do we add a new public class called “Student”
to this package.
18
BITS Pilani, Pilani Campus
Adding a Class to a Package

• Define the public class “Student” and place the package


statement before the class definition as follows:
package pack1;
package pack1;
public class Student{ class Teacher
// class body
} class Student

• Store this in “[Link]” file under the directory “pack1”.


• When the “[Link]” file is compiled, the class file will be
created and stored in the directory “pack1”. Now, the package
“pack1” will contain both the classes “Teacher” and
“Student”.

19
BITS Pilani, Pilani Campus
Packages and Name Clashing

• When packages are developed by different organizations, it is


possible that multiple packages will have classes with the
same name, leading to name classing.
package pack1; package pack2;

class Teacher class Student

class Student class Courses

• We can import and use these packages like:


– import pack1.*;
– import pack2.*;
– Student student1; // Generates compilation error
20
BITS Pilani, Pilani Campus
Handling Name Clashing

• In Java, name classing is resolved by accessing classes


with the same name in multiple packages by their
fully qualified name.
• Example:
import pack1.*;
import pack2.*;
[Link] student1;
[Link] student2;
Teacher teacher1;
Courses course1;

21
BITS Pilani, Pilani Campus
Extending a Class from Package

• A new class called “Professor” can be created by


extending the “Teacher” class defined the
package “pack1” as follows:
import [Link];
public class Professor extends Teacher{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}

22
BITS Pilani, Pilani Campus
Summary

• Packages allow grouping of related classes into


a single united.
• Packages are organised in hierarchical
structure.
• Packages handle name classing issues.
• Packages can be accessed or inherited without
actual copy of code to each program.

23
BITS Pilani, Pilani Campus
Object Oriented Programming

BITS Pilani Dr. Tanmaya Mahapatra


Department of Computer Science and Information Systems
Pilani Campus
Contents

• Nested & Inner Classes


• Anonymous Classes
• Static usages

CS F213 Object Oriented Programming 2


BITS Pilani, Pilani Campus
Nested Classes

• It is possible to define a class within another class.


• Such classes are known as nested classes.
• The scope of a nested class is bounded by the scope of its enclosing
class.
– If class B is defined within class A, then B does not exist independently of
A.
• A nested class has access to the members, including private
members, of the class in which it is nested.
• The enclosing class does not have access to the members of the
nested class.
1. A nested class that is declared directly within its enclosing class
scope is a member of its enclosing class.
2. It is also possible to declare a nested class that is local to a block.
CS F213 Object Oriented Programming 3
BITS Pilani, Pilani Campus
Nested Classes

• There are two types of nested classes: static and non-static.


• A static nested class is one that has the static modifier
applied.
1. It cannot refer to non-static members of its enclosing class
directly.
2. Static nested classes are seldom used.

CS F213 Object Oriented Programming 4


BITS Pilani, Pilani Campus
Inner Classes

• An inner class is a non-static nested class.


• It has access to all of the variables and methods of its outer
class.
• May refer to them directly in the same way that other non-
static members of the outer class do.
• Demo → [Link]
1. An instance of Inner can be created only in the context of
class Outer.
2. Else the Java compiler generates an error message.
3. An inner class instance is often created by code within its
enclosing scope

CS F213 Object Oriented Programming 5


BITS Pilani, Pilani Campus
Inner Classes → Local Classes

• It is possible to define inner classes within any block scope.


• Demo → [Link]

CS F213 Object Oriented Programming 6


BITS Pilani, Pilani Campus
Important Points

• It is possible to define a class within another class, such classes are


known as nested classes.
• The scope of a nested class is bounded by the scope of its enclosing
class.
• A nested class has access to the members, including private
members, of the class in which it is nested.
• The reverse is not true i.e., the enclosing class does not have access
to the members of the nested class.
• A nested class is also a member of its enclosing class.
• A nested class can be declared private, public, protected,
or package private(default).
• Nested classes are divided into two categories:
• static nested class: Nested classes that are declared static are called static
nested classes.
• inner class: An inner class is a non-static nested class.
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
Syntax

class OuterClass {
...
class NestedClass {
...
}
}

CS F213 Object Oriented Programming 8


BITS Pilani, Pilani Campus
Inner Class vs Static Nested Class

• In the case of normal or regular inner classes, without an


outer class object existing, there cannot be an inner class
object.
• An object of the inner class is always strongly associated with
an outer class object.
• But in the case of static nested class, Without an outer class
object existing, there may be a static nested class object.
• An object of a static nested class is not strongly associated
with the outer class object.
• Demo → StaticNestedClassDemo

CS F213 Object Oriented Programming 9


BITS Pilani, Pilani Campus
Inner Class

• To instantiate an inner class, we must first instantiate the


outer class.
• Then, create the inner object within the outer object with this
syntax:
– [Link] nnerObject = [Link] InnerClass();
• Demo → InnerClassDemo3

CS F213 Object Oriented Programming 10


BITS Pilani, Pilani Campus
Anonymous Classes

• Anonymous classes in Java are nested classes without a class name.


• They are typically declared as either subclasses of an existing class, or as
implementations of some interface.
• Anonymous classes are defined when they are instantiated.

Anonymous class doIt() is printed to


[Link]. The anonymous class subclasses
(extends) SuperClass and overrides the doIt()
method.

CS F213 Object Oriented Programming 11


BITS Pilani, Pilani Campus
Anonymous Classes

• A Java anonymous class can also implement an interface.


• An anonymous class implementing an interface is similar to an anonymous class
extending another class.
• An anonymous class can access members of the enclosing class.
• We can declare fields and methods inside an anonymous class, but cannot
declare a constructor.

CS F213 Object Oriented Programming 12


BITS Pilani, Pilani Campus
Anonymous Classes

• It is an class without a name and for which only a single


object is created.
• An anonymous class can be useful when making an instance
of an object with certain “extras” such as overriding methods
of a class or interface, without having to actually subclass a
class.
• The syntax of an anonymous class expression is like the
invocation of a constructor, except that there is a class
definition contained in a block of code.
• Demo → GFG, AnonymousDemo

CS F213 Object Oriented Programming 13


BITS Pilani, Pilani Campus
Syntax

// Test can be interface,abstract/concrete class


Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};

CS F213 Object Oriented Programming 14


BITS Pilani, Pilani Campus
Regular Class vs Anonymous

• A normal class can implement any number of interfaces but


the anonymous class can implement only one interface at a
time.
• A regular class can extend a class and implement any number
of interfaces simultaneously. But anonymous class can extend
a class or can implement an interface but not both at a time.
• For regular/normal class, we can write any number of
constructors but we can’t write any constructor for
anonymous class because the anonymous class does not have
any name and while defining constructor class name and
constructor name must be same.

CS F213 Object Oriented Programming 15


BITS Pilani, Pilani Campus
What has been covered?

• Nested & Inner Classes


• Anonymous Classes
• Static

CS F213 Object Oriented Programming 16


BITS Pilani, Pilani Campus
Object Oriented Programming

BITS Pilani Dr. Tanmaya Mahapatra


Pilani Campus Department of Computer Science and Information Systems
Contents

• Lambdas

CS F213 Object Oriented Programming 2


BITS Pilani, Pilani Campus
Lambdas: An Introduction

• A lambda expression is, essentially, an anonymous method.


• This method is not executed on its own.
• It is used to implement a method defined by a functional
interface.
• A lambda expression results in a form of anonymous class.
• Lambda expressions are also commonly referred to as
closures.
• A functional interface is an interface that contains one and
only one abstract method.
• A functional interface typically represents a single action.

CS F213 Object Oriented Programming 3


BITS Pilani, Pilani Campus
Lambdas

• Example: The standard interface Runnable is a functional


interface because it defines only one method: run( ).
Therefore, run( ) defines the action of Runnable.
• A functional interface is sometimes referred to as a SAM type,
where SAM stands for Single Abstract Method.
• Demo → Test

CS F213 Object Oriented Programming 4


BITS Pilani, Pilani Campus
Lambda Expressions

• The lambda expression introduced a new syntax element and


operator into the Java language.
• The lambda operator or the arrow operator, is −>.
• It divides a lambda expression into two parts.
• The left side specifies any parameters required by the lambda
expression. (If no parameters are needed, an empty parameter list
is used.)
• On the right side is the lambda body, which specifies the actions of
the lambda expression.
• The −> can be verbalized as “becomes” or “goes to.”
• Java defines two types of lambda bodies.
– One consists of a single expression, and the other type consists of a block
of code.

CS F213 Object Oriented Programming 5


BITS Pilani, Pilani Campus
Lambda Expressions

• () -> 123.45
• This lambda expression takes no parameters, thus the
parameter list is empty.
• It returns the constant value 123.45.
• It is similar to the following method:
• double myMeth() { return 123.45; }
• The method defined by a lambda expression does not have a
name.
• () -> [Link]() * 100
• This lambda expression obtains a pseudo-random value from
[Link]( ), multiplies it by 100, and returns the result
CS F213 Object Oriented Programming 6
BITS Pilani, Pilani Campus
Lambda Expressions

• When a lambda expression requires a parameter, it is


specified in the parameter list on the left side of the lambda
operator.
• (n) -> (n % 2)==0
• This lambda expression returns true if the value of parameter
n is even.
• It is possible to explicitly specify the type of a parameter but
often we won’t need to do so because in many cases its type
can be inferred.
• Like a named method, a lambda expression can specify as
many parameters as needed.
CS F213 Object Oriented Programming 7
BITS Pilani, Pilani Campus
Functional Interfaces

• A functional interface is an interface that specifies only one


abstract method.
• All interface methods are implicitly abstract.
• With JDK 8, it is possible to specify a default implementation
for a method declared in an interface.
• Private and static interface methods also supply an
implementation.
• Today, an interface method is abstract only if it does not
specify an implementation.
• Because non-default non-static, non-private interface
methods are implicitly abstract, there is no need to use the
abstract modifier (can be used though).
CS F213 Object Oriented Programming 8
BITS Pilani, Pilani Campus
Functional Interfaces: Example

CS F213 Object Oriented Programming 9


BITS Pilani, Pilani Campus
Lambda Expressions

• A lambda expression is not executed on its own.


• It forms the implementation of the abstract method defined by the functional
interface that specifies its target type.
• A lambda expression can be specified only in a context in which a target type is
defined.
• One of these contexts is created when a lambda expression is assigned to a
functional interface reference. (Demo → Test)
• Other target type contexts include variable initialization, return statements, and
method arguments etc.
• // Create a reference to a MyNumber instance.
• MyNumber myNum;
• Next, a lambda expression is assigned to that interface reference:
• // Use a lambda in an assignment context.
• myNum = () -> 123.45;

CS F213 Object Oriented Programming 10


BITS Pilani, Pilani Campus
Block Lambdas

• The body of the lambdas may consist of a single expression.


• These types of lambda bodies are referred to as expression
bodies, and lambdas that have expression bodies are
sometimes called expression lambdas.
• Sometimes the situation will require more than a single
expression.
• To handle such cases, Java supports a second type of lambda
expression in which the code on the right side of the lambda
operator consists of a block of code that can contain more
than one statement. This type of lambda body is called a block
body. Lambdas that have block bodies are sometimes referred
to as block lambdas.

CS F213 Object Oriented Programming 11


BITS Pilani, Pilani Campus
Block Lambdas

• A block lambda expands the types of operations that can be


handled within a lambda expression because it allows the
body of the lambda to contain multiple statements.
• For example, in a block lambda we can declare variables, use
loops, specify if and switch statements, create nested blocks
etc.
• Must explicitly use a return statement to return a value. This
is necessary because a block lambda body does not represent
a single expression.

CS F213 Object Oriented Programming 12


BITS Pilani, Pilani Campus
Demos

• Demos →
1. Lambda Demo 1
2. Lambda Demo 2
3. Lambda Demo 3
4. Block Lambda Demo 1
5. Block Lambda Demo 2
6. Anonymous Demo → Replace with Lambda example

CS F213 Object Oriented Programming 13


BITS Pilani, Pilani Campus
Passing Lambda Expression as
Arguments
• A lambda expression can be used in any context that provides
a target type.
• One of these is when a lambda expression is passed as an
argument.
• Passing a lambda expression as an argument is a common use
of lambdas.
• It is a very powerful use because it gives us a way to pass
executable code as an argument to a method.
• To pass a lambda expression as an argument, the type of the
parameter receiving the lambda expression argument must be
of a functional interface type compatible with the lambda.
• Demo → Lambdas As Arguments Demo
CS F213 Object Oriented Programming 14
BITS Pilani, Pilani Campus
Method Reference: Static Methods

• A method reference provides a way to refer to a method without


executing it.
• It relates to lambda expressions because it, too, requires a target type
context that consists of a compatible functional interface.
• When evaluated, a method reference also creates an instance of the
functional interface.
• To create a static method reference:
– ClassName::methodName
• The class name is separated from the method name by a double colon.
• The :: is a separator that was added to Java by JDK 8 expressly for this
purpose.
• This method reference can be used anywhere in which it is compatible
with its target type. (Demo → MethodRefDemo)

CS F213 Object Oriented Programming 15


BITS Pilani, Pilani Campus
Method Reference: Instance
Methods

• To pass a reference to an instance method on a specific


object:
• objRef::methodName
• The syntax is similar to that used for a static method, except
that an object reference is used instead of a class name.
• (Demo → MethodRefDemo2)

CS F213 Object Oriented Programming 16


BITS Pilani, Pilani Campus
Lambdas & Variable Capture

• Variables defined by the enclosing scope of a lambda


expression are accessible within the lambda expression.
• For example, a lambda expression can use an instance or
static variable defined by its enclosing class.

CS F213 Object Oriented Programming 17


BITS Pilani, Pilani Campus
Lambdas & Variable Capture

• Demo → VarCapture
• When a lambda expression uses a local variable from its
enclosing scope, a special situation is created that is referred
to as a variable capture.
• A lambda expression may only use local variables that are
effectively final.
• An effectively final variable is one whose value does not
change after it is first assigned.
• A local variable of the enclosing scope cannot be modified
by the lambda expression.
• Doing so would remove its effectively final status, thus
rendering it illegal for capture.
CS F213 Object Oriented Programming 18
BITS Pilani, Pilani Campus
What has been covered?

• Lambdas✔

CS F213 Object Oriented Programming 19


BITS Pilani, Pilani Campus

You might also like