UNIT-2: Inheritance, Interface and Package

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

UNIT-2

Inheritance, Interface and Package


Inheritance 2

• Inheritance is one of the three foundational principles of object-


oriented programming.
• Using inheritance, you can create a general class that defines
traits common to a set of related items.
• class that is inherited is called a SUPERCLASS.
• The class that does the inheriting is called a SUBCLASS.
• A subclass is a specialized version of a superclass. It inherits all of
the variables and methods defined by the superclass and add its
own unique elements.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
3

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


Basics 4

• Java supports inheritance by allowing one class to incorporate


another class into its declaration. This is done by using the
“extends” keyword.
• Example program
• A class will be declared private to prevent its unauthorized use or
tampering.
• Inheriting a class does not overrule the private access restriction.
• even though a subclass includes all of the members of its
superclass, it cannot access those members of the superclass that
have been declared private.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
Access specifiers 5

• Public
• Private
• Protected ( protected members can be accessed only by sub
classes).
• NOTE: Variables, methods, and constructors, which are
declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of
the protected members' class.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


CONSTRUCTORS AND INHERITANCE 6

• The constructor for the superclass constructs the superclass


portion of the object, and the constructor for the subclass
constructs the subclass part.
• This makes sense because the superclass has no knowledge of or
access to any element in a subclass. Thus their construction must
be separate.
• When only the subclass defines a constructor, then it constructs
the subclass object. The superclass portion of the object is
constructed automatically using its default constructor.
• Example program
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
7

• When both superclass and subclass defines the constructors, the


use java keyword super to executes both constructors.
• super has 2 forms:
• calling superclass constructor.
• access a member of the superclass that has been hidden by a member of a
subclass.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


USING super TO CALL SUPERCLASS
CONSTRUCTOR: 8

• A subclass can call a constructor defined by its superclass by use of the


following form of super:
super(parameter-list);
• parameter-list specifies any parameters needed by the constructor in the
superclass.
• NOTE: super() must always be the first statement executed inside a subclass
constructor.
• Example program
• Any form of constructor defined by the superclass can be called by super(). The
constructor executed will be the one that matches the arguments.
• Example program
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
USING super TO ACCESS SUPERCLASS
MEMBERS: 9

• super always refers to the superclass of the subclass in which it is


used.
syntax: super.member
• This form of super is most applicable to situation in which member
names of a subclass hide members by the same name in the
superclass.
• Example program

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


CREATING A MULTILEVEL HIERARCHY 10

• You can build hierarchies that contain as many layers class

of inheritance as you like. A

• subclass will act as superclass for another subclass. class

class

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


POLYMORPHISM 11

• Method overloading:
If a class has multiple methods having
same name but different in parameters,
it is known as Method Overloading.

• Method Overriding:
If subclass (child class) has
the same method as declared in the
super class(parent class), it is known
as method overriding.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
POLYMORPHISM 12

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


overridden method is resolved at run time rather than compile time. ( this
helps you to implement run time polymorphism). In this process, an
overridden method is called through the reference variable of a superclass.
• Method overriding is a perfect example of runtime polymorphism. Since
in method overriding both the classes(base class and child class) have same
method, compile doesn’t figure out which method to call at compile-time.
In this case JVM(java virtual machine) decides which method to call at
runtime that’s why it is known as runtime or dynamic polymorphism.
• Compile time polymorphism is nothing but the method overloading in java.
In simple terms we can say that a class can have more than one methods
with same name but with different number of arguments or different types
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS

of arguments or both.
class sup {
void show() { System.out.println("super class method"); }
}
class sub1 extends sup {
void show() { System.out.println(" sub class -1 method"); }
13
}
class sub2 extends sup {
void show() { System.out.println(" sub class -2 method"); }
}
class demo {
public static void main(String[] s) {
sup superob = new sup();
sub1 subob1 = new sub1();
sub2 subob2 = new sub2();
sup supref; What’s the output?
supref = superob;
supref.show();
supref = subob1;
supref.show();
supref = subob2;
supref.show();
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
}
}
FINAL keyword 14

• to prevent a method from being overridden or a class from being


inherited by using the keyword final.
• for example, class is used to define private variables with some
initialization values. and we don't want to change those values
further (even by using their subclass).
• final prevents :
• Overriding
• Inheritance
• using final with Data Members.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
final prevents overriding 15

• to prevent a method from being overridden, specify final as a


modifier at the start of its declaration.
• methods declared as final cannot be overridden.
• Example:
class A {
final void show() { System.out.println(" super class method"); }
}
class B extends A {
void show() { } //it will give error, it cannot be override.
}
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
final prevents inheritance 16

• To prevent a class from being inherited by preceding its


declaration with final.
• Declaring a class as final implicitly declares all of its methods as
final.
• Example:
final class A {
// body of class A
}
class B extends A { // it gives error.
//body of class B
}
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
using final with Data Members 17

• if you precede a class variables name as final, its value cannot be


changed throughout the lifetime of your program.
• NOTE: we can declare final member variables as static also.
example: static final int i = 10;
• NOTE: we can use final on method parameters and local variables.
so that it prevents changing the value within the method.
declaring a local variable final prevents it from being assigned a
value more than once.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


OBJECT CLASS 18

• Java defines one special class called Object that is an implicit


superclass of all other classes.
• It means that a reference variable of type object can refer to an
object of any other class.
• Object defines some methods, which means that they are
available in every object.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


METHOD PURPOSE
Object clone() Creates a new object that is same as the

boolean equals(Object obj)


object being cloned.
Determines whether one object is equal to
19
another.
void finalize() Called before a unused object is recycled.

final Class <?> getClass() Obtains the class of an object at runtime.

int hashCode() Returns the hash code associated with the


invoking object.
final void notify() Resumes execution of a thread waiting on the
invoking object.
final void notifyAll() Resumes execution of all thread waiting on
the invoking object.
String toString() Returns a string that describes the object.

final void wait() Waits on another thread of execution.


final void wait(long millisecs)
final void wait(long millisecs, int nanosecs)
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
Important methods in Object class 20

• equals():
• it compares 2 objects.
• returns true if objects are equivalent.
• it checks if the invoking reference refers to the same object as the one
passed as an argument.
• this method is overridden to determine if 2 objects are equal in their
contents.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


Important methods in Object class 21

• toString():
• returns a string that contains a description of the object on which it is
called.
• this method is automatically called when an object is output using println().
• notice the unusual syntax in the return type for getClass().this relates to
java's generic features. generics allow the type of data used by a class or
method to be specified as a parameters.
• valueOf():
• depend on the passed parameters. This method returns the string
representation of the passed argument.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


DYNAMIC BINDING 22
• Connecting a method call to the method body is known as binding.
• There are two types of binding
• static binding(or early binding).
• dynamic binding(or late binding).
• static binding:
• When type of the object is determined at compiled time(by the compiler),
it is known as static binding.
• If there is any private, final or static method in a class, there is static
binding.
• dynamic binding:
• When type of the object is determined at run-time, it is known as dynamic
binding.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS

• Homework: Compare and contrast static binding and dynamic binding.


ABSTRACT CLASS 23

• Creating a superclass that defines only a generalized form that


will be shared by all of its subclasses, leaving it to each subclass
to fill in the details.
• Abstract class determines the nature of the methods that the
subclasses must implement but does not itself provide an
implementation of one or more of these methods.
• An abstract method is created by specifying the abstract type
modifier.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


ABSTRACT CLASS 24

• An abstract method contains no body and is, therefore, not


implemented by the superclass.
• To declare an abstract method, syntax is : abstract type
name(parameter-list);
• NOTE: the abstract modifier can be used on normal methods. it
cannot be applied to static methods or to constructors.
• NOTE: A class that contains one or more abstract methods must
also be declared as abstract by preceding its class declaration
with the abstract specifier.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
ABSTRACT CLASS 25

• Since an abstract class does not define a complete implementation, there can
be no objects of an abstract class (it will give compilation error, if you create an
object for abstract class).
• When a subclass inherits an abstract class, it must implement all of the abstract
methods in the superclass. If it doesn't, then the subclass must also be specified
as abstract. Thus, the abstract attribute is inherited until such time as a
complete implementation is achieved.
• NOTE: it is illegal to declare a class as both abstract and final since an abstract
class is incomplete by itself and relies on its subclasses to provide complete
implementation.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


PACKAGES 26

• A package is a group of related classes and interfaces.


• packages help organize your code and provide another layer of
encapsulation.
• A package servers 2 purposes:
• It provides a mechanism by which related pieces of a program can be
organized as a unit.
• A package participates in java's access control mechanism.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


27

• Classes defined within a package


must be accessed through their
package name.
• Advantages of package: it avoids
name collisions with other classes.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


DEFINING A PACKAGE 28

• A package defines a namespace, the name of a class that you put


into the package will be in that package's namespace.
• Syntax: package p1; //p1 is the name of the package.
• NOTE: To create a package, you will use the package statement
which is located at the top of the source file.
• Java uses the file system to manage packages, with each package
stored in its own directory.
• The package statement simply specifies to which package the file
belongs.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
29

• 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.
• example: package p1.p2.p3;
• Of course, you must create directories that support the package
hierarchy that you create.
• by default, the run time system uses the current working directory
as its starting point.
• note: you will need to be in the directory just above the package
when you are executing.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
PACKAGES AND MEMBER ACCESS 30

Private Default Protected Public


Visible within same class Yes Yes Yes yes
Visible within same package by No Yes Yes Yes
subclass

Visible within same package by No Yes Yes Yes


non-subclass

Visible within different package No No Yes yes


by subclass

Visible within different package No No No yes


by non-subclass
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
importing packages 31

• using import, you can bring one or more members of a package


into view. This allows you to use those members directly, without
explicit package qualification.
• syntax: import pkg.classname; or import pkg.*;
• import with the keyword static, an import stmt can be used to
import the static members of a class or interface. This is called
static import.
• for example: import static java.lang.Math.sqrt;
• Homework: Describe about how to find packages and CLASSPATH.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
INTERFACE 32

• Interface defines what a class must do but not how it will do it.
• In java, an interface defines set of methods that will be
implemented by a class.
• interfaces are similar to abstract classes, except that no method
can include a body.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


syntax 33

• An interface is declared by use the interface keyword.


access interface name {
ret-type method-name1(parameter-list);
ret-type method-name2(parameter-list);
|
|
ret-type method-nameN(parameter-list);
}
• access -> either public or not used (because it makes them
accessible to the widest range of code).
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
34

• In an interface, methods are declared using only their return type


and signature. They are essentially abstract methods.
• once an interface is defined, any number of classes can implement
it. This makes it possible for 2 or more classes to provide the same
functionality even though they might do so in different ways.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


35
• To implement an interface, follow these 2 steps:
• in a class declaration, include an implements clause that specifies
the interface being implemented.
• inside the class, implement the methods defined by the interface.
• syntax: class classname extends superclass implements interface
{
• //class-body
• }
• extends is optional (it enables to inherit the class)
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
36

• NOTE: To implement more than one interface, the interfaces are


separated with a comma.
• NOTE: the methods that implement an interface must be declared
public. Also, the return type and signature of the implementing
method must match exactly the return type and signature
specified in the interface declaration.
• NOTE: only obligation a class has when implementing an interface
is to provide the methods defined by the interface. It is not
limited to provide only those methods. The class can provide
whatever additional functionality is desired.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
Variables in Interface 37

• Variables declared in interface are always PUBLIC, FINAL and


STATIC and must be initialized. ( act as constants in
implementing classes).

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


Interfaces can be extended 38

• One interface can inherit another by use of the keyword extends.


• when a class implements an interface that inherits another
interface, it must provide implementations for all methods
defined within the interface inheritance chain.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


NESTED INTERFACE 39

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


a class. such an interface is called a member interface or nested
interface.
• An interface nested in a class can use any access modifier.
• An interface nested in another interface is implicitly public.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


Difference between Interface and abstract
class 40
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstractmethods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main method or
method and constructor. constructor.
5) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
6) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS

You might also like