Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

DEPT & SEM : CSE & I SEM

SUBJECT NAMEOBJECT ORIENTED PROGRAMMING


: THROUGH JAVA

19A05303T
COURSE CODE :
II
UNIT :
P LAKSHMI
PREPARED BY :
CONCEPTS:
• Inheritance Basics, Using Super, Creating Multilevel hierarchy,

• Method overriding, Dynamic Method Dispatch,

• Using Abstract classes, Using final with inheritance, Object


class,

• Packages Basics, Finding packages and CLASSPATH,

• Access Protection, Importing packages.

• Interfaces Definition, Implementing Interfaces,

• Extending Interfaces, Nested Interfaces,

• Applying Interfaces, Variables in Interfaces.


COURSE: OOPJ UNIT: I1 Pg. 2
INHERITANCE

 “Reusability” is one of the important property of oop.


 Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object.
 The idea behind inheritance in java is that you can create new classes that are built
upon existing classes.
 The old class is called “base class/super class/parent class” and new class is called
“derived class/sub class/child class”.
 In inheritance object is created for sub class only.
 When a class hierarchy is created constructors complete their execution in order of
derivation, from super class to subclass.

COURSE: OOPJ UNIT: I1 Pg. 3


SYNTAX OF JAVA INHERITANCE

class Subclass-name extends Superclass-name

//methods and fields

TYPES OF INHERITANCE IN JAVA:

1. Single inheritance

2. Multilevel inheritance

3. Hierarchical inheritance

4. Multiple inheritance(java does not support )

5. Hybrid inheritance

COURSE: OOPJ UNIT: I1 Pg. 4


TYPES OF INHERITANCE IN JAVA

IS-A

Fig . 2.1

COURSE: OOPJ UNIT: I1 Pg. 5


Fig . 2.2

COURSE: OOPJ UNIT: I1 Pg. 6


class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
} }
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) { OUT PUT :
int a = 20, b = 10; The sum of the given numbers:30
My_Calculation demo = new My_Calculation(); The difference between the given
demo.addition(a, b); numbers:10
The product of the given
demo.Subtraction(a, b);
numbers:200
demo.multiplication(a, b);
}} COURSE: OOPJ UNIT: I1 Pg. 7
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:
weeping...
barking...
eating... COURSE: OOPJ UNIT: I1 Pg. 8
8
USING SUPER

1. USING SUPER TO CALL SUPERCLASS CONSTRUCTORS


 A subclass can call a constructor defined by its super class by use of the following
form of super:

super(arg-list);

Box class Code

class BoxWeight extends Box

double weight; // weight of box

BoxWeight(double w, double h, double d, double m) {

super(w, h, d); // call super class constructor

}
COURSE: OOPJ UNIT: I1 Pg. 9
2. ACCESSING SUPER CLASS MEMBERS
//super.member (varible/method)
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
i = b; // i in B
super.i = a; // i in A
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
} OUT PUT;
}
class UseSuper { i in superclass: 1
public static void main(String args[]) { i in subclass: 2
B subOb = new B(1, 2);
subOb.show();
} }
COURSE: OOPJ UNIT: I1 Pg. 10
METHOD OVERRIDING

 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.

USAGE OF JAVA METHOD OVERRIDING:

 Method overriding is used to provide specific implementation of a method that is


already provided by its super class.

 Method overriding is used for runtime polymorphism


RULES FOR JAVA METHOD OVERRIDING:

 method must have same name as in the parent class

 method must have same parameter as in the parent class.

 must be IS-A relationship (inheritance).

Note:
 Subclass is override the super class method
COURSE: OOPJ UNIT: I1 Pg. 11
NON OVERRIDING OVERRIDING

class Vehicle{ class Vehicle{


void run() void run()
{System.out.println("Vehicle is runni {System.out.println("Vehicle is running
ng");} ");}
} }
class Bike extends Vehicle{ } class Bike2 extends Vehicle{
class BikeMain(){ void run()
public static void main(String args[]){ {System.out.println("Bike is running sa
Bike obj = new Bike(); fely");}

obj.run(); public static void main(String args[]){

} } Bike2 obj = new Bike2();

Output:Vehicle is running obj.run();


COURSE: OOPJ UNIT: I1 Pg. 12
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.

Ex:

A obj=new B(); // A is the reference class for obj, the object is created for B

obj.show();// call B class show method.

COURSE: OOPJ UNIT: I1 Pg. 13


DYNAMIC METHOD DISPATCH EXAMPLE
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
} }
COURSE: OOPJ UNIT: I1 Pg. 14
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // create a reference to A – initially r is NULL ,linking is done at runtime
r = a; // r refers to an A object – “runtime polymorphism “
r.callme(); // calls A's version of callme - “Dynamic method dispatch”
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}}
The output from the program is shown here:
Inside A's callme method
Inside B's callme method
Inside C's callme method
COURSE: OOPJ UNIT: I1 Pg. 15
USING FINAL WITH INHERITANCE

 Using final to Prevent Overriding

 Methods declared as final cannot be overridden.


class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}

COURSE: OOPJ UNIT: I1 Pg. 16


USING ABSTRACT CLASSES
 A method with method body is called “Concrete method”.
 A method with out method body is called “abstract method”.
 A class that contain Abstract method is called “Abstract Class”.
 The Abstract method and Classes should be declared using keyword “abstract”.
 If we want to implement same name methods differently ,then we use abstract
methods.
 It is possible to implement the abstract methods differently in the sub classes of an
abstract class.
 To declare a class abstract , we simply use the abstract keyword infront of the class
keyword.
 An abstract class have both abstract and concrete methods.
 We can not create the object to the abstract class , because it is not fully defined.
Syntax:
abstract class classname
abstrct type method-name(parameter list); COURSE: OOPJ UNIT: I1 Pg. 17
A SIMPLE DEMONSTRATION OF ABSTRACT.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme(); OUTPUT:
b.callmetoo(); B's implementation of callme
} This is Concreate method
}

COURSE: OOPJ UNIT: I1 Pg. 18


THE OBJECT CLASS

 There is one special class, Object, defined by Java. All other classes are subclasses
of Object.

 That is, Object is a superclass of all other classes.

 Object defines the following methods, which means that they are available in
every object

COURSE: OOPJ UNIT: I1 Pg. 19


COURSE: OOPJ UNIT: I1 Pg. 20
PACKAGES
 A Package is nothing but a directory that contain classes and interfaces.
 Packages act as “Container” for classes.
 Packages provide “Security “ and “Reusability”.
 Java use the “File System” directory to store packages.
 Packages Separate the classes and interfaces so, we can use the same class name
for different packages.
Exp: java.util.Date;
java.sql.Date;
PACKAGE CREATION :
 To create a package simply include a package command as the first statement in a
Java source file.
 Syntax: package packagename;
Exp: package pack;
package MyPackage;
 The general form of a multileveled package
package pkg1[.pkg2[.pkg3]];
Exp: package java.awt.image;

COURSE: OOPJ UNIT: I1 Pg. 21


STEPS TO CREATION OF PACKAGE:
1. Declare the package at the beginning of a file using the form “package packagename;”
2. Define the classes
3. Crete the subdirectory under the main directory with package name.
4. Store the program with .java extension in main directory.
5. Compile the file.
Finding Packages and CLASSPATH :
For example, consider the following package specification:
 package MyPack
For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
 then the class path to MyPack is
C:\MyPrograms\Java
COMPILE AND EXICUTE PACKAGE
 Compilation: javac –d . filename.java
 Execution: java MyPack .AccountBalance
COURSE: OOPJ UNIT: I1 Pg. 22
Access Control / Access Protection :

 Access means visibility, if you do not have access to a class you


cannot use any methods or variables of that class.

 Java provide Access Modifiers to access class.

 packages, Java addresses four categories of visibility for class


members:

• Subclasses in the same package

• Non-subclasses in the same package

• Subclasses in different packages

• Classes that are neither in the same package nor subclasses


23
COURSE: OOPJ UNIT: I1 Pg. 23
Access Modifiers

Access Modifier Class or member can be


referenced by…
public methods of the same class, and
methods of other classes
Private methods of the same class only

Protected methods of the same class, methods


of subclasses, and methods of
classes in the same package
default No access methods in the same package only
modifier (package
access)

COURSE: OOPJ UNIT: I1 Pg. 24


default access modifier
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package.
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
} }
In the above example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
COURSE: OOPJ UNIT: I1 Pg. 25
Quick lookup table to show the access to members permitted by each modifier

Subclass
Modifier Class Package World

public Y Y Y Y

protected Y Y Y N

no modifier
Y Y N N
(default)

private Y N N N

26
COURSE: OOPJ UNIT: I1 Pg. 26
A SIMPLE PACKAGE
package MyPack;
public class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
COURSE: OOPJ UNIT: I1 Pg. 27
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
} }

28
COURSE: OOPJ UNIT: I1 Pg. 28
PACKAGE IMPORTING :

 We can access the classes of the package by importing.


 In java source file ,”import” statements occur immediately following the package
statements.
 Syntax: import pkg1 [.pkg2].(classname | *);
Exp1: import java.util.Date;
import java.io.*;
Exp2:
package MyPack1;
Import Mypack.*;
Class AccountBalance1
{
------
-----
}
COURSE: OOPJ UNIT: I1 Pg. 29
30
COURSE: OOPJ UNIT: I1 Pg. 30
31
COURSE: OOPJ UNIT: I1 Pg. 31
INTERFACES
 An interface in java is a blueprint of a class. It has static constants and abstract
methods.
 The interface in java is a mechanism to achieve abstraction.
 There can be only abstract methods in the java interface not method body. It is
used to achieve abstraction and multiple inheritance in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class
WHY USE JAVA INTERFACE?
 There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.

COURSE: OOPJ UNIT: I1 Pg. 32


 The java compiler adds public and abstract keywords before the interface method.
More, it adds public, static and final keywords before data members.

UNDERSTANDING RELATIONSHIP BETWEEN CLASSES AND INTERFACES:


 a class extends another class, an interface extends another interface but a class
implements an interface

Fig . 2.3
COURSE: OOPJ UNIT: I1 Pg. 33
GENERAL FORM OF TO CREATE AN INTERFACE:

[visibility] interface Interface -name

[extends other Interface]

variable declarations;

abstract method declarations;

}
GENERAL FORM OF TO IMPLEMENT AN INTERFACE:

[visibility] class class –name implements interface name

// definition of class

COURSE: OOPJ UNIT: I1 Pg. 34


JAVA INTERFACE EXAMPLE
 In this example, Printable interface has only one method, its implementation is provide
in the A class.

interface printable{

void print();

class A6 implements printable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

A6 obj = new A6();

obj.print();

}
COURSE: OOPJ UNIT: I1 Pg. 35
MULTIPLE INHERITANCE IN JAVA BY INTERFACE

 If a class implements multiple interfaces, or an interface extends multiple interfaces


i.e. known as multiple inheritance.

Fig . 2.4

COURSE: OOPJ UNIT: I1 Pg. 36


interface Printable{ interface Printable{
void print(); void print();
} }
interface Showable{ interface Showable{
void show(); } void print();
class A7 implements Printable,Showable{ }
public void print() class A7 implements Printable,Showable{
{System.out.println("Hello");}
public void show() public void print()
{System.out.println("Welcome");} {System.out.println("Hello");}
public static void main(String args[]){ public static void main(String args[]){
A7 obj = new A7(); A7 obj = new A7();
obj.print(); obj.print();
obj.show(); }
} } }
Test it Now Test it Now
Output Output
:Hello Welcome :Hello

COURSE: OOPJ UNIT: I1 Pg. 37


EXTENDING INTERFACE
 A class implements interface but one interface extends another interface .
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
} }
Output:
Hello Welcome
COURSE: OOPJ UNIT: I1 Pg. 38
JAVA DEFAULT METHOD IN INTERFACE

 Since Java 8, we can have method body in interface. But we need to make it default
method. Let's see an example:
File: TestInterfaceDefault.java
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle in interface");
public void drawRect(){System.out.println("drawing rectanglein class");
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Output:
drawing rectangle
default method
COURSE: OOPJ UNIT: I1 Pg. 39
 Notice that variable d is declared to be of the interface type Drawable,
 yet it was assigned an instance of Rectangle. Although d can be used to access the
draw and msg methods,
 it cannot access any other members of the Client class. An interface reference
variable has knowledge only of the methods declared by its interface declaration.
Thus, d could not be used to access drawRect( ) since it is defined by Rectangle but
not Drawable.
MARKER OR TAGGED INTERFACE
 An interface that have no member is known as marker or tagged interface.
 For example: Serializable, Cloneable, Remote etc. They are used to provide some
essential information to the JVM so that JVM may perform some useful operation.
 //How Serializable interface is written?
public interface Serializable
{
} COURSE: OOPJ UNIT: I1 Pg. 40
NESTED INTERFACE IN JAVA

 An interface can have another interface i.e. known as nested interface. We will
learn it in detail in the nested classes chapter.

interface printable

void print();

interface MessagePrintable

void msg();

COURSE: OOPJ UNIT: I1 Pg. 41


USE STATIC METHODS IN AN INTERFACE

 JDK 8 added another new capability to interface: the ability to 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.
 Thus, no implementation of the interface is necessary, and no instance of the
interface is required, in order to call a static method.
 Instead, a static method is called by specifying the interface name, followed by a
period, followed by the method name.
 Here is the general form:

 InterfaceName.staticMethodName

COURSE: OOPJ UNIT: I1 Pg. 42


public interface MyIF {
// This is a "normal" interface method declaration.
// It does NOT define a default implementation.
int getNumber();
// This is a default method. Notice that it provides
// a default implementation.
default String getString()
{
return "Default String";
}
// This is a static interface method.
static int getDefaultNumber() { return 0; }
}
NOTE:
The getDefaultNumber( ) method can be called, as shown here:
int defNum = MyIF.getDefaultNumber();

COURSE: OOPJ UNIT: I1 Pg. 43


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.

For example:

abstract class Incomplete implements Callback {

int a, b;
interface Callback
void show() { {
void callback(int param);
System.out.println(a + " " + b);
Void show();
} }

//...

}
 Here, 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.
COURSE: OOPJ UNIT: I1 Pg. 44
VARIABLES IN INTERFACES

Interface variables are static because java interfaces cannot be instantiated on their
own. The value of the variable must be assigned in a static context in which no
instance exists.

The final modifier ensures the value assigned to the interface variable is a true
constant that cannot be re-assigned. In other words, interfaces can declare only
constants, not instance variables.
CONTENT BEYOND SYLLABUS

STATIC KEYWORD

 The static keyword in java is used for memory management mainly.


The static can be:
•variable (also known as class variable)
• The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,college
name of students etc.
•method (also known as class method)
• A static method can be invoked without the need for creating an instance of
a class(object).
•Block
•It is executed before main method at the time of class loading

COURSE: OOPJ UNIT: I1 Pg. 46


CONTENT BEYOND SYLLABUS

VARARGS: VARIABLE-LENGTH ARGUMENTS

The varrags allows the method to accept zero or muliple arguments.


 Before varargs (Beginning with JDK 5) either we use overloaded method or
take an array as the method parameter but it was not considered good
because it leads to the maintenance problem
Advantage of Varargs:
 We don't have to provide overloaded methods so less code.
Syntax of varargs:
return_type method_name(data_type... variableName){ }

COURSE: OOPJ UNIT: I1 Pg. 47


CONTENT BEYOND SYLLABUS
EXAMPLE PROGRAM FOR VARARGS:
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length + " Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Notice how an array must be created to
// hold the arguments. The output from the program is shown here:
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = { }; Number of args: 1 Contents: 10
vaTest(n1); // 1 arg Number of args: 3 Contents: 1 2 3
vaTest(n2); // 3 args Number of args: 0 Contents:
vaTest(n3); // no args
}
}
48
COURSE: OOPJ UNIT: I1 Pg. 48
Overloading Vararg Methods

You can overload a method that takes a variable-length argument.

// Varargs and overloading.

class VarArgs3 {

static void vaTest(int ... v) {

System.out.print("vaTest(int ...): " +

"Number of args: " + v.length +

" Contents: ");

for(int x : v)

System.out.print(x + " ");

System.out.println();

}
49
COURSE: OOPJ UNIT: I1 Pg. 49
static void vaTest(String msg, int ... v) {

System.out.print("vaTest(String, int ...): " +

msg + v.length +

" Contents: ");

for(int x : v)

System.out.print(x + " ");

System.out.println();

public static void main(String args[])

vaTest(1, 2, 3);

vaTest("Testing: ", 10, 20);

vaTest(true, false, false); 50


COURSE: OOPJ UNIT: I1 Pg. 50
UNIT OUTCOMES:

Student should be able to

 Implement types of Inheritance and developing new classes based on existing


classes
 Distinguish between system packages and user defined packages.
 Demonstrate features of interfaces to implement multiple inheritances.

COURSE: OOPJ UNIT: I1 Pg. 51


DIGITAL RESOURCES

 Lecture Notes - Lecture Notes

 Video Lectures - Video Lecture

 E-Book - Java The Complete Reference Ninth Edition

 Model Papers - JNTUA Question Papers

COURSE: OOPJ UNIT: I1 Pg. 52


THANK YOU

COURSE: OOPJ UNIT: I1 Pg. 53

You might also like