0% found this document useful (0 votes)
37 views69 pages

Oops - Unit - III

The document discusses inheritance in Java including concepts like subclasses inheriting from superclasses, the use of keywords like 'super' and 'this', method overriding and abstract classes. It also covers packages, interfaces, and the usage of the 'final' keyword with inheritance, classes, methods and variables. Examples are provided to illustrate inheritance, method overriding, and usage of 'super' and 'this'.
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)
37 views69 pages

Oops - Unit - III

The document discusses inheritance in Java including concepts like subclasses inheriting from superclasses, the use of keywords like 'super' and 'this', method overriding and abstract classes. It also covers packages, interfaces, and the usage of the 'final' keyword with inheritance, classes, methods and variables. Examples are provided to illustrate inheritance, method overriding, and usage of 'super' and 'this'.
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
You are on page 1/ 69

UNIT-III

• Inheritance, Packages and Interfaces


• Inheritance Basic concepts, member access rules
• Usage of “super”, “this” keyword
• Forms of inheritance
– method overriding
– abstract classes
• Dynamic method dispatch
• Using “final” with inheritance
• The Object class
• Defining, Creating and Accessing a Package
• Understanding CLASSPATH, importing packages
• Differences between classes and interfaces
– defining an interface, implementing interface
– applying interfaces
– variables in interface and extending interfaces
Inheritance
• A class that is inherited is called a superclass. The class that
does the inheriting is called a subclass.

• Therefore, 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.

• To inherit a class, you simply incorporate the definition of


one class into another by using the extends keyword.

• Although a subclass includes all of the members of its


superclass, it cannot access those members of the
superclass that have been declared as private.
public class ClassA {

public static void main(String[] args)


{
ClassA objA = new ClassA();
objA.methA();
}

public void methA()


{
System.out.println("Method A of Class-A");
}
}
public class ClassB {

public static void main(String[] args)


{
ClassB objB = new ClassB();
objB.methB();
}

public void methB()


{
System.out.println("Method B of Class-B");
}
}
public class ClassA {
public static void main(String[] args) {
ClassA objA = new ClassA();
objA.methA();
}

public void methA() {


System.out.println("Method A of Class-A"); }
}
-------------------------------------------------
public class ClassB {
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methB();
}

public void methB() {


System.out.println("Method B of Class-B"); }
}
public class ClassB {
public static void main(String[] args) {
ClassA objA = new ClassA();
ClassB objB = new ClassB();
objA.methA(); //calling methA of ClassA
objB.methB(); //calling methB of ClassB
}

public void methB() {


System.out.println("Method B of Class-B");
}
}
public class ClassB extends ClassA{
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methB(); //calling methB of ClassB
objB.methA(); //calling methA of ClassA
}

public void methB() {


System.out.println("Method B of Class-B");
}
}
X
public class ClassB extends ClassA{
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methA(); //calling methA of Class ??
objB.methB(); //calling methB of ClassB
}

public void methB()


{ System.out.println("Method B of Class-B"); }

public void methA()


{ System.out.println("Method A of Class-B"); }
}

Which methA() will be called ???


public class ClassB extends ClassA{
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methA(); //calling methA of ClassB
objB.methB(); //calling methB of ClassB
}

public void methB()


{ System.out.println("Method B of Class-B"); }

public void methA()


{ System.out.println("Method A of Class-B"); }
}

Which methA() will be called ???


Method Overriding

• Usage of Java Method Overriding


– Method overriding is used to provide the specific
implementation of a method which is already
provided by its superclass.
– Method overriding is used for runtime polymorphism
• Rules for Java Method Overriding
– The method must have the same name as in the
parent class
– The method must have the same parameter as in the
parent class.
– There must be an IS-A relationship (inheritance).
Overriding vs Overloading
Sl. No. Method Overloading Method Overriding
Is performed within class. occurs in two classes that
1 have inheritance
relationship.
parameter must be parameter must be same.
2
different.
Is an example of compile Is an example of run time
3
time polymorphism. polymorphism.
Ex. area(double r), Ex. methodA() in ClassA,
4. area(double L, double B) methodA() in ClassB
both in same class extends ClassA

Run-Time vs Compile-Time
super & this
• Whenever a subclass needs to refer to its
immediate superclass, it can do so by use of
the keyword super.
• super has two general forms :
– The first calls the ‘superclass’ constructor.
– The second is used to access a member of the
superclass that has been hidden by a member of a
subclass.
• We can use this as well as super anywhere
except static area.
This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
• When a subclass calls super(), it is calling the
constructor of its immediate superclass.
• Thus, super() always refers to the superclass
immediately above the calling class. This is true
even in a multileveled hierarchy.
• Also, super() must always be the first statement
executed inside a subclass constructor.
• super() can also be used to call methods that are
hidden by a subclass.
• Here is given the 6 usage of java this keyword.
– this can be used to refer current class instance
variable.
– this can be used to invoke current class method
– this can be used to invoke current class
constructor.
– this can be passed as an argument in the method
call.
– this can be passed as argument in the constructor
call.
– this can be used to return the current class
instance from the method.
public class ClassB extends ClassA{
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methX();
}
public void methA()
{ System.out.println("Method-A of Class-B"); }
public void methB()
{ System.out.println("Method B of Class-B"); }

public void methX() {


super.methA();
this.methA();
}
}
public class ClassA {

int x = 10;
public static void main(String[] args) {
System.out.println("Method A of Class-A");
}
}
------------------------------------------------------
public class ClassB extends ClassA{

int x = 20;
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methB();
}

public void methB() {


System.out.println("Super X is : " + super.x);
System.out.println("This X is : " + this.x);}
}
“final” keyword
• The final keyword in java is used to restrict
the user. The java final keyword can be used in
many context.
– Variable
• If you make any variable as final, you cannot change
the value of final variable(It will be constant).
– Method
• If you make any method as final, you cannot override it.
– Class
• If you make any class as final, you cannot extend it.
public class ClassA {
final int x = 10;
public static void main(String[] args) {
<body>
}
}
-------------------------------------------------
“final”
public class ClassB extends ClassA{ variable
int x = 20;
public static void main(String[] args) {
<body> The value of variable
} “x” in ClassA CANNOT
be changed by the
public void methB() { variable “x” of ClassB
super.x = 22; ERROR because the value of
“x” in ClassA becomes
<body>
constant as it is
} declared “final”
public class ClassA { “final”
final void methA() method
{ <body> }
}

-------------------------------------------------------------------------------------------------------
------------
public class ClassB extends ClassA{

public static void main(String[] args) { The methodA of ClassA


ClassB objB = new ClassB(); CANNOT be overridden
objB.methA(); ERROR by the methodA of
ClassB because
} methodA of ClassA is
declared “final”
public void methA()
{ <body> }
}
“final”
final class A { class
public void methA()
{ System.out.println("Method A of Class-A"); }
}

---------------------------------------------------------------------------------------------
public class B extends A{ ERROR

public static void main(String[] args) {


B b = new B();
The ClassA CANNOT be
b.methA(); extended or inherited
} by ClassB because
ClassA is declared
} “final”
public class ClassA {
final int x = 10;
public static void main(String[] args) {
System.out.println("Method A of Class-A");
}
}
-------------------------------------------------
“final”
public class ClassB extends ClassA{ variable
int x = 20;
public static void main(String[] args) {
ClassB b = new ClassB();
b.methB();
}

public void methB() {


super.x = 22; ERROR
System.out.println("Super X is : " + super.x);
System.out.println("This X is : " + this.x);}
}
public class A {
“final”
public static void main(String[] args) {
A a = new A();
method
a.methA();
}

final void methA()


{
System.out.println("Method A of Class-A");
}
}

-------------------------------------------------------------------------------------------------------------------------------

public class B extends A{

public static void main(String[] args) {


B b = new B();
b.methA(); ERROR
}

public void methA()


{
System.out.println("Method A of Class-B");
}
}
final class A {
“final”
public static void main(String[] args) {
A a = new A();
class
a.methA();
}

public void methA()


{
System.out.println("Method A of Class-A");
}
}

-------------------------------------------------------------------------------------------------------------------------------

public class B extends A{ ERROR


public static void main(String[] args) {
B b = new B();
b.methA();
}

public void methA()


{
System.out.println("Method A of Class-B");
}
}
PACKAGES
&

Access Specifiers
PACKAGE

• A mechanism for partitioning the class name


space into more manageable chunks.
• The package is both a naming and a visibility
control mechanism.
• You can define classes inside a package that are
not accessible by code outside that package.
• You can also define class members that are
exposed only to other members of the same
package.
PACKAGE
• To create a package, simply include a package
command as the first statement in a Java source file.
Any classes declared within that file will belong to the
specified package.
• This is the general form of the package statement:
package <pkg-name>;
• The package statement defines a name space in which
classes are stored. If you omit the package statement,
the class names are put into the default package.
• While the default package is fine for short, sample
programs, it is inadequate for real applications. Most of
the time, you will define a package for your code.
PACKAGE
• Java uses file system directories to store
packages.
• More than one file can include the same package
statement.
• The package statement simply specifies to which
package the classes defined in a file belong.
• It does not exclude other classes in other files
from being part of that same package.
• Most real-world packages are spread across many
files.
PACKAGE
• You can create a hierarchy of packages. To do so, simply
separate each package name from the one above it by use
of a period. The general form of a multileveled package
statement is shown here:
package pkg1[.pkg2[.pkg3]];

• A package hierarchy must be reflected in the file system of


your Java development system. For example, a package
declared as package java.awt.image; needs to be stored in
java\awt\image in a Windows environment.

• Be sure to choose your package names carefully. You


cannot rename a package without renaming the directory
in which the classes are stored.
pkg1
pkg2
Class1
meth1()

Class2
meth2()
pkg1a

SuperClass Super class


main()

SubClass
Sub class
subMeth()
package pkg1;

public class Class1 {


public static void main(String[] args) {
Class1 obj1 = new Class1();
obj1.meth1();
}

public void meth1()


{ System.out.println(“Class-1 Package - 1");}
}
package pkg2;

public class Class2 {


public static void main(String[] args) {
Class2 obj2 = new Class2();
obj2.meth2();
}

public void meth2()


{ System.out.println("Iam in Package - 2");}
}
package pkg1;
import pkg2.Class2;
// import pkg2.*;

public class Class1 {


public static void main(String[] args) {
Class1 obj1 = new Class1();
Class2 obj2 = new Class2();

obj1.meth1();
obj2.meth2();
}

public void meth1()


{ System.out.println("Iam in Package - 1"); }
}
package pkg1.pkg1a;
import pkg2.Class2;
import pkg1.Class1;

public class SuperClass {


public static void main(String[] args) {
System.out.println(“Super Class");
Class1 obj1 = new Class1();
Class2 obj2 = new Class2();
SubClass sub = new SubClass();

Class1.meth1();
Class2.meth2();
sub.subMeth();
}
}
package pkg1.pkg1a;
public class SubClass extends
SuperClass {

public void subMeth()


{
System.out.println("Iam in SubClass");
}
}
Access Specifiers
• Encapsulation
• Prevent the misuse of the data
• Related mostly to inheritance or packages.
– (A package is, essentially, a grouping of classes.)
• Java’s access modifiers are
– public, private, protected and default
•The private access modifier is accessible only within
class.

•If you don't use any modifier, it is treated as default. The


default modifier is accessible only within package.

•The protected access modifier is accessible within


package and outside the package but through inheritance
only.

•The public access modifier is accessible everywhere. It


has the widest scope among all other modifiers.
pkg1 pkg2

Class1
meth1() Class2
meth2()

pkg1a
Super class • public
SuperClass • private
main() • protected
Sub class • default
SubClass
subMeth()
pkg1 pkg2

Class1
meth1() Class2
meth2()

pkg1a
Super class • public
SuperClass • private
main() • protected
Sub class • default
SubClass
subMeth()
pkg1 pkg2

Class1
meth1() Class2
meth2()

pkg1a
Super class • public
public
SuperClass •• private
private
• protected
main() • protected
• default
Sub class • default
SubClass
subMeth()
pkg1 pkg2

Class1
meth1() Class2
meth2()

pkg1a
Super class • public
SuperClass • private
main() • protected
Sub class • default
SubClass
subMeth()
pkg1 pkg2

Class1
meth1() Class2
meth2()

pkg1a
Super class • public
SuperClass • private
main() • protected
Sub class • default
SubClass
subMeth()
INTERFACES
&
Abstract Classes
INTERFACES

• Using interface, you 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.
INTERFACES

• To implement an interface, a class must


provide the complete set of methods required
by the interface.
• Each class is free to determine the details of
its own implementation.
• Java allows you to fully utilize the “one
interface, multiple methods” aspect of
polymorphism.
INTERFACES

• In order for a method to be called from one


class to another, both classes need to be
present at compile time.
• This makes for a static and non-extensible
classing environment.
• Functionality gets pushed up higher and
higher in the class hierarchy so that the
mechanisms will be available to more and
more subclasses.
INTERFACES
• Interfaces are designed to avoid this
problem.
• They disconnect the definition of a method
or set of methods from the inheritance
hierarchy.
• Since interfaces are in a different hierarchy
from classes, it is possible for classes that
are unrelated in terms of the class hierarchy
to implement the same interface.
public class ClassA {
public static void main(String[] args) {
ClassA objA = new ClassA();
objA.methA();
}
public void methA() {
System.out.println("Method A of Class-A"); }
}
------------------------------------------------------
public class ClassB extends ClassA{
public static void main(String[] args) {
ClassB objB = new ClassB();
objB.methB();
objA.methA(); Method Overriding
}
public void methB() {
System.out.println("Method B of Class-B"); }
public void methA() {
System.out.println("Method A of Class-B"); }
}
public class ClassA {
public static void main(String[] args)
{ // code }
public void methA()
{ // code }
}
-------------------------------------------------
public class ClassB {
public static void main(String[] args)
{ // code }
public void methA()
{ // code }
}
-------------------------------------------------
public class ClassC extends ClassA, ClassB {
public static void main(String[] args)
{ // code }
public void methA() //which superclass method will be Overridden ??

{ // code }
}
public class Circle {
public static void main(String[] args)
{ // code }
public void area()
{ // code }
}
-------------------------------------------------
public class Rectangle {
public static void main(String[] args)
{ // code }
public void area()
{ // code }
}
-------------------------------------------------
public class Polygon extends Circle, Rectangle {
public static void main(String[] args)
{ // code }
public void area() //which superclass method will be Overridden ??

{ // code }
}
public interface ClassA {
public static void main(String[] args)
{ // code }
public void methA() ;
}
-------------------------------------------------------
public interface ClassB {
public static void main(String[] args)
{ // code }
public void methA() ;
}
------------------------------------------------------
public class ClassC implements ClassA, ClassB {
public static void main(String[] args)
{ // code }
public void methA() //which superclass method will be Overridden ??
{ // code }
}
Defining an Interface
An interface is defined much like a class.
This is a simplified general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;

}
• Java does not support MULTIPLE
Classes but it supports MULTIPLE
Interfaces.

• You cannot EXTEND Multiple Classes


but can IMPLEMENT Multiple
Interfaces
public interface Bank{
float rateOfInterest();
}

public class SBI implements Bank{


public float rateOfInterest(){ return 9.15f; }
}

public class PNB implements Bank{


public float rateOfInterest(){ return 9.7f; }
}

public class InterfaceDemo{


public static void main(String[] args){
SBI sbi = new SBI();
System.out.println("ROI: "+ sbi.rateOfInterest());
}
}
Interfaces Can Be Extended
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. Following is an example:

interface A {
void meth1();
void meth2();
}

interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {

public void meth1()


{ System.out.println("Implement meth1().");}

public void meth2()


{ System.out.println("Implement meth2().");}

public void meth3()


{ System.out.println("Implement meth3()."); }
}
Abstraction in Java
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user. It shows only important
things to the user and hides the internal details.
– ex. sending sms, you just type the text and send the
message. You don't need to know the internal
processing about the message delivery

• There are two ways to achieve abstraction in java


• Abstract class (0 to 100%)
• Interface (100%)
Abstract Classes
• An abstract class is a class that is
declared abstract — it may or may not include
abstract methods.
• Abstract classes cannot be instantiated, but
they can be subclassed.
• When an abstract class is subclassed, the
subclass usually provides implementations for
all of the abstract methods in its parent class.
• A class that is declared as abstract is known
as abstract class.
• It needs to be extended and its method
implemented.
• It cannot be instantiated.

• A method that is declared as abstract and


does not have implementation is known as
abstract method.
Abstract Class

• A class which contains the abstract keyword in


its declaration is known as abstract class.
• Abstract classes may or may not
contain abstract methods, i.e., methods without
body ( public void get(); )
• But, if a class has at least one abstract method,
then the class must be declared abstract.
• If a class is declared abstract, it cannot be
instantiated.
• To use an abstract class, you have to inherit it
from another class, provide implementations to
the abstract methods in it.
• If you inherit an abstract class, you have to
provide implementations to all the abstract
methods in it.
abstract class Bike{
abstract void run();
}

class Honda extends Bike{


public void run()
{ System.out.println("running safely.."); }
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}
Syntax
• Interface Syntax
interface name{
//methods
}

• Abstract Class Syntax


abstract class name{
// code
}
Abstract Classes Interfaces
Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
A Javaabstract classcan have class members Members of a Java interface are public by
like private, protected, etc. default.
An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interface only.
interfaces.
An abstract class can be extended using An interface class can be implemented
keyword "extends". using keyword "implements".
Variables in Interfaces
• In Java, interface doesn't allow you to declare any
instance variables.
• Using a variable declared in an interface as an
instance variable will return a compile time error.
• You can declare a constant variable, using static final
which is different from an instance variable
• You 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 you include that interface in a class (that is,
when you “implement” the interface), all of those
variable names will be in scope as constants.
Dynamic Method Dispatch
• Method overriding forms the basis for one of
Java’s most powerful concepts:
– 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.
• Normally, 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.
Late binding (run-time)
public static void main(String[] args) {
A a = new A();
B b = new B();
a.methA();
b.methA();
Early binding (compile-time)
final void methA()
{ System.out.println("Method A of Class-A"); }
UNIT – III
COMPLETED

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy