KEMBAR78
Java Unit - Ii | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
16 views32 pages

Java Unit - Ii

java

Uploaded by

sunilyadhav201
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)
16 views32 pages

Java Unit - Ii

java

Uploaded by

sunilyadhav201
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/ 32

22PC1IT201 UNIT - II OOP Through Java

SYLLABUS
Inheritance, Packages, Interfaces and Other Topics: Understanding static, Introducing Nested and Inner
classes, Access Modifiers, Varargs: variable-Length Arguments, Lambda Expressions, garbage collection-
finalize.
Inheritance: Basics, using super, creating a multi-level hierarchy, when constructors are executed, method
overriding, polymorphism - dynamic method dispatch, using abstract class, final with Inheritance, object
class.
Packages and Interfaces: Packages, Access protection, Importing Packages, Interfaces, Default Interfaces,
Default interface methods, Use static methods in an Interface.

Inheritance, Packages, Interfaces and Other Topics


Understanding static
• The static is a keyword in Java is used for memory management.
• When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
• We can apply java static keyword with variables, methods, blocks and nested class.
• The static keyword belongs to the class than an instance (object) of the class.
• Static members can be accessible both within a class and outside of it by name and class name,
respectively.
• Characteristics:
✓ Shared memory allocation
✓ Accessible without object instantiation
✓ Associated with class, not objects
✓ Cannot access non-static members

1) static variable (class variable)


1. A variable that declared with static keyword is known as a static variable.
2. When a variable is declared as static, then a single copy of variable is created and shared among all
objects at class level.
3. The static variable gets memory only once in the class area at the time of class loading.
4. Syntax:
static datatype variablename;

2) static method (class method)


1. A method that declared with static keyword is known as a static method.
2. The most common example of a static method is main( ) method.
3. Restrictions:
➢ They can only directly call other static methods.
➢ They can only directly access static variable.
➢ They cannot refer to this or super in any way.
Syntax:
static returntype method_name(par-list) {
//body;
}

1
22PC1IT201 UNIT - II OOP Through Java

3) static block
1. static block used to initialize the static data member.
2. It is executed before the main method at the time of class loading.
Syntax:
static{
Body;
}
Example: Demonstrate static variables, methods, and blocks.
class UseStatic
{
static int a = 3;
static int b;
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void main (String args[])
{
meth(42);
}
}
Output:
Static block initialized.
x = 42
a=3
b = 12

2
22PC1IT201 UNIT - II OOP Through Java

Nested and Inner classes


• A class is placed into another class is called nested class.
Syntax: class OuterClassName
{
//data;
//code;
class NestedClassName
{
//data;
//code;
}
}
Nested classes are divided into two types:
1. Non-static nested classes (Inner class): A non-static class is placed into a class is called inner class.
Example:// Demonstrate an inner class.
class College{ //outer class
static String name = "VNR";
public void test( ){
System.out.println("College name :"+name);
}
class Student{ //outer class(non-static)
String name = "Apple";
String rollno = "22071a6901";
public void disply( ){
System.out.println("Student name :"+name);
System.out.println("Student rollno :"+rollno);
}
}
}
class Demo{
public static void main(String[] args) {
College c = new College( ); //object for outer class
c.test( );
College.Student s = c.new Student( ); //object for inner class
s.disply( );
}
}
Output:
College name :VNR
Student name :Apple
Student rollno :22071a6901

Note: If you want create instance for inner class you must create instance for outer class.

3
22PC1IT201 UNIT - II OOP Through Java

2. Static nested classes (Nested class): A static class is placed into a class is called nested class.
Example:// Demonstrate an inner class.
class College{
static String name = "VNR";
public void test( ){
System.out.println("College name :"+name);
}
static class Student{
String name = "Apple";
String rollno = "22071a6901";
public void disply( ){
System.out.println("Student name :"+name);
System.out.println("Student rollno :"+rollno);
}
}
}
class Demo{
public static void main(String[] args) {
College c = new College( ); //object for outer class
c.test();

College.Student s = new College.Student( ); //object for inner class


s.disply( );
}
}
Output:
College name :VNR
Student name :Apple
Student rollno :22071a6901

4
22PC1IT201 UNIT - II OOP Through Java

Access Modifiers
• ••
Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member.
• It provides security, accessibility, etc. to the user depending upon the access modifier used with the
element.
• There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
• When no access modifier is specified for a class, method, or data member the it having
the default access modifier by default.
• The default access modifiers are accessible only within the same package.
2. Private Access Modifier
• The private access modifier is specified using the keyword private.
• The private access modifiers are accessible only within the class in which they are declared.
• Any other class of the same package will not be able to access these members.
3. Protected Access Modifier
• The protected access modifier is specified using the keyword protected.
• The protected access modifiers are accessible within the same package or subclasses in different
packages.
4. Public Access modifier
• The public access modifier is specified using the keyword public.
• The protected access modifiers are accessible everywhere in the program. There is no restriction on
the scope of public data members

5
22PC1IT201 UNIT - II OOP Through Java

Lambda Expressions
• A lambda expression is an anonymous (i.e., unnamed) method.
• When using a lambda expression, we can provide the implementation without having to create the
method once more.
• lambda expression is used to implement a method defined by a functional interface.
• A functional interface is an interface that contains one and only one abstract method.
• A functional interface is sometimes referred to as a SAM (Single Abstract Method) type.
• Advantages are providing the implementation of Functional interface and Less coding.
• syntax: (argument-list) -> {body};
Example: Testing the number
interface NumericTest{
void test(int n);
}
class LambdaExp {
public static void main(String[] args) {

//test the number is even or odd


NumericTest obj = (n)->{
if(n%2==0)
System.out.println("Even number");
else
System.out.println("Odd number");
};
obj.test(5);

//test the number is Positive or Negative


obj = (n)->{
if(n>2==0)
System.out.println("Positive number");
else
System.out.println("Negative number");
};
obj.test(5);
}
}
Output:
Odd number
Positive number

6
22PC1IT201 UNIT - II OOP Through Java

Garbage Collection
Garbage Collection
• The Garbage Collection is used to reclaim the memory of unreferenced object automatically.
• Garbage collection occurs periodically or occasionally during the execution of your program.
• How can an object be unreferenced?
➢ By nulling the reference
➢ By assigning a reference to another
➢ By anonymous object etc.
finalize( ) method:
• The finalize( ) method is invoked each time before the object is garbage collected.
• This method can be used to perform cleanup processing.
Syntax: protected void finalize( )
{
// finalization code here
}
gc( ) method:
• The gc( ) method is used to invoke the garbage collector to perform cleanup processing.
Syntax: public static void gc( ){}

Example: Simple Example of garbage collection in java

class TestGarbage1
{
public void finalize( )
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1( );
TestGarbage1 s2=new TestGarbage1( );
s1=null;
s2=null;
System.gc( );
}
}

7
22PC1IT201 UNIT - II OOP Through Java

Varargs: Variable-Length Arguments


• A method that takes a variable number of arguments is called a variable arguments method, or varargs
method.
• A variable-length argument is specified by three periods (…).
• The varrags allows the method to accept zero or muliple arguments.
• Before varargs 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.
• If we don't know how many arguments we will have to pass in the method, varargs is the better approach.
Rules for varargs:
• There can be only one variable argument in the method.
• Variable argument (varargs) must be the last argument.
Example: Demonstrate variable-length arguments.
class VarArgs
{
static void vaTest(int ... v)
{
System.out.print("Number of args: " + v.length +" Contents: ");
for(int x : v)
System.out.println(x + " "); Output:
System.out.println( );
} Number of args: 1 Contents: 10
public static void main(String args[]) Number of args: 3 Contents: 1 2 3
{ Number of args: 0 Contents:
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}

Example: A method can have variable length parameters with other parameters

class Student1{
static void result(String name, int...marks){
int sum = 0;
for(int i:marks){
sum +=i;
}
System.out.println("Student name :"+name);
System.out.println("Total Number of arguments :"+marks.length);
System.out.println("Total marks :"+sum);
} Output:
}
public class MethodOverloading { Student name :Apple
public static void main(String args[]) { Total Number of arguments :5
Student1.result("Apple",10,20,30,50,60); Total marks :170
Student1.result("Mango",60,70,80,90); Student name :Mango
} Total Number of arguments :4
} Total marks :300

8
22PC1IT201 UNIT - II OOP Through Java

Inheritance
Inheritance Basics
• Inheritance is a mechanism to obtaining the one class properties into another class and it creates new
class from existing class.
(Or)
• Inheritance is a mechanism to obtaining the one object properties into another object and it creates
new class from existing class.
• The class which is giving properties is called base class(or) parent class (or) super class.
• The class which is taking properties is called derived class (or) child class (or) sub class.
• Inheritance is basically used for reducing the overall code size of the program (code reusability).

Derived class:
• The class which is taking properties is called derived class (or) child class (or) sub class.
• Syntax:
class Derivedclass-name extends Baseclass-name
{
//data and code
}
• The extends keyword indicates that you are making a new class that derives from an existing class.
• The meaning of "extends" is to increase the functionality.

Why Do We Need Java Inheritance?


✓ Code Reusability
✓ Polymorphism.
✓ Abstraction
Types of inheritance: There are 5 types of inheritances.
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance

1. Single inheritance
Single derived class with only one base class, is called single inheritance.
(Or)
A class inherits members of only one class is called single inheritance.
Example program:
class Base {
public void add(int x, int y) {
System.out.println("Addition of x and y :"+(x+y));
}
}
class Derived extends Base {
public void sub(int x, int y) {
System.out.println("Subtraction of x and y :"+(x-y));
}
9
22PC1IT201 UNIT - II OOP Through Java

}
class SingleInheritance {
public static void main(String args[]) {
public int x = 10 , y = 20;
Derived obj=new Derived();
obj.add(x,y);
obj.sub(x,y);
}
}
Output:
Addition of x and y :30
Subtraction of x and y :-10

2. Multiple inheritance
A derived class with several base class, is called multiple inheritance.
(Or)
A class inherits members of two or more classes is called multiple inheritance.
Note: Multiple inheritance achieved through interface, not classes
Example:
interface Car{
void drive( );
}
interface Bike{
void ride( );
}
public class Person implements Car, Bike {
@Override
public void drive( ) {
System.out.println("Test drive completed by person");
}
@Override
public void ride( ) {
System.out.println("Test ride completed by person");
}
public static void main(String args[]) {
Person obj = new Person ( );
obj.drive();
obj.ride();
}
}
Output:
Test drive completed by person
Test ride completed by person

10
22PC1IT201 UNIT - II OOP Through Java

3. Hierarchical inheritance
Several derived classes with only one base class is called hierarchical inheritance.
(Or)
Two or more classes inherits members of only one class is called hierarchical inheritance.
Example program:
class Base {
int x = 10,y = 20;
public void display( ) {
System.out.println("x value:"+x);
System.out.println("y value:"+y);
}
}
class Derived1 extends Base {
public void Biggest( ) {
if(x>y)
System.out.println("biggest number is:"+x);
else
System.out.println("biggest number is:"+y);
}
}
class Derived2 extends Base {
public void mean( ) {
float z = (x + y)/2;
System.out.println("The mean of the given numbers:"+z);
}
}
class HierachielInheritance {
public static void main(String args[]) {
Derived1 obj1 = new Derived1();
obj1.display();
obj1.Biggest();

Derived2 obj2 = new Derived2();


obj2.display();
obj2.mean();
}
}
Output:
x value:10
y value:20
biggest number is:20
x value:10
y value:20
The mean of the given numbers:15.0

11
22PC1IT201 UNIT - II OOP Through Java

4. Multilevel inheritance
A derived class with another derived class is called multilevel inheritance.
(Or)
A class inherits members another derived class is called multilevel inheritance.

Example program:

class Base
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
}
class Derived1 extends Base
{
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
class Derived2 extends Derived1
{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
}
class MultilevelInheritance
{
public static void main(String args[])
{
int a=10, b=20;
Derived2 obj = new Derived2();
obj.addition(a, b);
obj.Subtraction(a, b);
obj.multiplication(a, b);
}
}
Output:
The sum of the given numbers:30
The difference between the given numbers:-10
The product of the given numbers:200
12
22PC1IT201 UNIT - II OOP Through Java

5. Hybrid inheritance
The combination of two or more inheritances is called hybrid inheritance.
Example:

class GrandFather { //parent class


public void showG( ) {
System.out.println("He is grandfather.");
}
}
class Father extends GrandFather { //inherits GrandFather properties
public void showF( ) {
System.out.println("He is father.");
}
}
class Son extends Father { //inherits Father properties
public void showS( ) {
System.out.println("He is son.");
}
}
public class Daughter extends Father { //inherits Father properties
public void showD( ) {
System.out.println("She is daughter.");
}
public static void main(String args[]) {
Son obj = new Son( ); Output:
obj.showS( ); // Accessing Son class method He is son.
obj.showF( ); // Accessing Father class method He is father.
obj.showG( ); // Accessing GrandFather class method He is grandfather.
Daughter obj2 = new Daughter( ); She is daughter.
obj2.showD( ); // Accessing Daughter class method He is father.
obj2.showF( ); // Accessing Father class method He is grandfather.
obj2.showG( ); // Accessing GrandFather class method
}
}
13
22PC1IT201 UNIT - II OOP Through Java

Constructors and inheritance


• As we know the constructors are never participate in inheritance.
• However, we must first complete initialization if we want to perform an operation, because a superclass
has no knowledge of any subclass.
• Constructors complete their execution in order of derivation, from base class to derived class i.e, the
constructor of the base class is executed first.
• Since super( ) must be the first statement executed in a derived class 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 base class will be executed.

Example: Demonstrate when constructors are executed.


class A { //base class
A( ) {
System.out.println("Inside A's constructor.");
}
}
class B extends A { //derived class
B( ) {
System.out.println("Inside B's constructor.");
}
}
class C extends B { //derived class
C( ) {
System.out.println("Inside C's constructor.");
} Output
}
class CallingCons { Inside A's constructor Inside
public static void main(String args[]) { B's constructor
C c = new C(); Inside C's constructor
}
}
• If super(par) is used, then the parameterized constructor of base class will be executed not default or
parameterless constructor.
class A { //base class
A( ) {
System.out.println("Inside A's constructor.");
}
A( String name) {
System.out.println("Inside A's constructor with name :"+name);
}
}
class B extends A { //derived class
B( ) { Output
super(“Apple”);
Inside A's constructor with name :Apple
System.out.println("Inside B's constructor.");
} Inside C's constructor.
class Student {
public static void main(String args[]) {
B c = new B( );
}
}
14
22PC1IT201 UNIT - II OOP Through Java

super keyword

• The super keyword refers to base class objects.


• super( ) calls the base class constructor.
• super.methodname( ) calls method from derived class.
• It is used to solve the ambiguity (confusion) between base class and derived class variables.
Example: Demonstrate the super keyword
class Example1
{
String color;
public Example1( ) {
color="white";
}
}
class Example2 extends Example1
{
String color="black";
public Example2( ) {
super();
}
public void display( )
{
System.out.println("derived class color :"+color);
System.out.println("base class color :"+super.color);
}
}
class SuperDemo
{
public static void main(String args[])
{
Example2 obj=new Example2( );
obj.display( );
}
}

Output:
derived class color :black
base class color :white

15
22PC1IT201 UNIT - II OOP Through Java

POLYMORPHISM
• Polymorphism is a Greek term (poly means many and morphs means forms), polymorphism as ability to
take an object into multiple form.
• Polymorphism can be achieved by method overloading, operator overloading, and method
overloading.
• Note: Java does not support operator overloading.

Compile time polymorphism (or) Early binding (or) Static binding:

• The compiler links the method call to the code (or) method definition at compile time is called compile
time polymorphism.
• In compile time polymorphism execution is fast.
• Compile time polymorphism can be achieved by method overloading, and operator overloading.

Run time polymorphism (or) Late binding (or) Dynamic binding:


• The compiler links the method call to the code (or) method definition at run time is called run time
polymorphism.
• In run time polymorphism execution is slow.
• Run time polymorphism can be achieved by method overriding.

Dynamic method dispatch:


• A mechanism in which call the derived class override method by using the base class reference is
called dynamic method dispatch.
• Dynamic method dispatch resolved at runtime polymorphism.

16
22PC1IT201 UNIT - II OOP Through Java

Method Overriding
• A derived class has the same method heading (return type, name, and parameters) as a method in its base
class, then the method in the derived class is said to override the method in the base class.
• Method overriding is allows a derived class to provide its own implementation for a method that is also
declared in its base class.
• This can be used to provide a specific implementation for a method that is common to all derived classes
of a particular class.
• Method overriding is a powerful feature that can be used to customize the behavior of a subclass.
Rules for method overriding:
✓ Base class and derived class method headings must be same.
✓ There must be an IS-A relationship (inheritance).
✓ If a method cannot be inherited then it cannot be overridden.
✓ Instance methods can be overridden only if they are inherited by the subclass.
✓ A method declared static cannot be overridden but can be re-declared.
✓ The method in base is need not to inherit in derived class.
Limitations:
• we cannot override main method.
• we cannot override static method.
• we cannot override final method.
Example: Demonstrate the method overriding
class Swapping1{
void swap(int a, int b){
int temp = a;
a = b;
b= temp;
System.out.println("Swapping 1 After swapping :a="+a+" and b="+b);
}
}
class Swapping2 extends Swapping1{
@Override
void swap(int a, int b){
a = a+b;
b = a-b;
a = a-b;
System.out.println("Swapping 2 After swapping :a="+a+" and b="+b);
}
}
class MethOverriding extends Swapping2{
public static void main(String[] a) {
Swapping1 s2 = new Swapping2(); //dynamic method dispatch
s2.swap(30,40);
}
}
Output:
Swapping 2 After swapping :a=40 and b=30

17
22PC1IT201 UNIT - II OOP Through Java

Abstraction
• The process of showing the functionality and hiding the implementation details is called abstraction.
(or)
• The mechanism of showing the necessary data and hiding the unnecessary data is called abstraction.
• The abstraction is achieved through abstract and interface keywords in java.
• The advantage of abstraction is readability and data hiding.

Understand abstract
• The abstract keyword is used to define abstract methods and abstract classes.
abstract method:
• A method having declaration without any implementation or body is called abstract method.
• Abstract methods are declared using abstract keyword ends with semicolon (;).
• Syntax: abstract type name(parameter-list);
abstract class:
• A class having at least one abstract method is called abstract class.
• abstract class can have member along with abstract method.
• Abstract classes can have constructors. However, it can call in concrete derived classes.
• Abstract class are defined using abstract keyword.
• Syntax: abstract class classname
{
//data & code
//abstract methods
}
Characteristics:
• All abstract method in abstract class must be implement in derived class, or else they will become
abstract too.
• We can’t create object for abstract class but create reference.
• Abstract classes are mainly used for provide an interface for its derived classes.
Limitation:
• An abstract keyword cannot be used with variables and constructors.
• We cannot use the abstract keyword with the final.
• We cannot declare abstract methods as private, and static.
• An abstract method can't be synchronized.

Example: Demonstrate the abstract class and abstract method


abstract class Swapping{
int x, y;
public void display( ){
System.out.println("x = "+x+" and y = "+y);
}
abstract void swap( );
}

18
22PC1IT201 UNIT - II OOP Through Java

public class AbstractDemo extends Swapping {


void swap( ) {
x = x + y;
y = x - y;
x = x - y;
}
public static void main(String[] args) {
AbstractDemo obj = new AbstractDemo();
obj.x = 10;
obj.y = 20;
System.out.println("Before Swapping");
obj.display();
System.out.println("After Swapping");
obj.swap();
obj.display();
}
}

Output:
Before Swapping
x = 10 and y = 20
After Swapping
x = 20 and y = 10

19
22PC1IT201 UNIT - II OOP Through Java

Understand final
• The final is a keyword which is a non-access modifier used to restrict the user.
• The final keyword can be applied with the variables, methods and classes.
final class:
• When a class is declared with final keyword, it is called a final class.
• A final class cannot be inherited.
Example: Demonstrate final class
final class A{

}
class B extends A{

}
public class FinalClass {
public static void main(String args[]) {
new B();
}
}
Output: Compile time error
cannot inherit from final A

final method:
• When a method is declared with final keyword, it is called a final method.
• A final method cannot be overridden.
Example: Demonstrate final method
class A{
public final void display( ){
System.out.println("Base class display");
}
}
class B extends A{
public final void display( ){
System.out.println("Base class display");
}
}
public class FinalMethod {
public static void main(String args[]) {
new B().display();
}
}
Output: Compile time error
java: display( ) in B cannot override display() in A
overridden method is final

Advantages: Immutability, easier to understand, and security

20
22PC1IT201 UNIT - II OOP Through Java

final Variables
• final variables are used to create constant variables.
• If you make any variable as final, you cannot change the value once it was initialized.
• You can initialize a final variable when it is declared or in constructor only.
• If your class having multiple constructors then it must be initialized in all constructor.
• A final variable that is not initialized during declaration is called blank final.
• A blank final static variable can be initialized inside a static block.
• If the final variable is a reference, then the variable cannot reference another object, but the internal
state of the object pointed by that reference variable can be changed.
• Syntax:
final <datatype> <variable name>=<value>; //final variable
final <datatype><variable name>; //blank final variable
static final <datatype><variable name>=<value>;//final static variable
Example: final double PI = 3.14;

Example: Demonstrate the final variable


public class Intern
{
final int SALARY=10000;
void change( ){
SALARY=10500;
}
public static void main(String args[]){
Intern i=new Intern();
i.change();
}
}
Output: Compile Time Error

Example: Demonstrate the final reference variable

class Final_Reference_Demo{
public static void main(String[] args)
{
final int[] arr = { 1, 2, 3, 4, 5 };
arr[4] = 1;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+”\t”);
}
}
}

Output: 1 2 3 4 1

21
22PC1IT201 UNIT - II OOP Through Java

The Object Class


• Object is a base class of all other classes.
• This means that a reference variable of type Object can refer to an object of any other class.
• Object defines the following methods, which means that they are available in every object.

Note:
• The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
• You may override the others.

22
22PC1IT201 UNIT - II OOP Through Java

Packages and Interfaces


Packages
• package is a group of related classes and interfaces.
• It helps prevent naming conflicts, make searching for classes easier, and provide controlled access.
• Packages are help to achieve the encapsulation.
Defining a 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.
• 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, which has no
name.
• Syntax: package pkg;
• Example: package MyPack;
• Java uses file system directories to store packages.
• The .class files for any classes you declare to be part of MyPack must be stored in a directory called
MyPack.
• Here the directory name must match the package name exactly.
• 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.
• A package hierarchy must be reflected in the file system of your Java development system.
• Syntax: package pkg1[.pkg2[.pkg3]];
• Example: pacakage MyPack.Maths.MyPack;
• The .class files needs to be stored in MyPack\Maths\ MyPack in a Windows environment.
Example: Demonstrate the package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.println(name + ": $" + bal);
}
}
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();
}
}
Note: File Location: C:\personal\MyPack\AccountBalance.java
23
22PC1IT201 UNIT - II OOP Through Java

Finding Packages and CLASSPATH


• The Java run-time system know where to look for packages that you create in four ways.
1. First, by default, the Java run-time system uses the current working directory as its starting point.
Thus, if your package is in a subdirectory of the current directory, it will be found.

2. Second, you can specify a directory path or paths by setting the CLASSPATH environmental
variable.

3. Third, you can use the -classpath option with java and javac to specify the path to your classes.

24
22PC1IT201 UNIT - II OOP Through Java

4. Third, you can use the -d option with java and javac to specify the path to your classes.

Importing Packages
• To use any predefined or user-defined classes that are already present in the packages, you must import
them.
to import package you need to use the import keyword.
• Syntax: import pkg1 [.pkg2].(classname | *);
• Example: import java.util.Scanner;
• There are three ways to access the package from outside the package.
1. Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
Example:
Source Code: A.java
package pack;
public class A{
public void msg( ){
System.out.println("Hello");
}
}

Source Code: B.java


import pack.*;
class B{
public static void main(String args[]) {
A obj = new A( );
obj.msg( );
}
}
Output:Hello

25
22PC1IT201 UNIT - II OOP Through Java

2. Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example:

Source Code: A.java


package pack;
public class A{
public void msg( ){
System.out.println("Hello");
}
}
Source Code: B.java
import pack.A;
class B{
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
Output:Hello

3. Using fully qualified name


• If you use fully qualified name then only declared class of this package will be accessible.
• Now there is no need to import. But you need to use fully qualified name every time when you
are accessing the class or interface.
• Example:

Source Code: A.java


package pack;
public class A{
public void msg( ){
System.out.println("Hello");
}
}
Source Code: B.java
class B{
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:Hello

26
22PC1IT201 UNIT - II OOP Through Java

Interfaces
• An interface is a reference type and it has static constants and abstract methods.
• The interface is a mechanism to achieve abstraction and multiple inheritance.
• An interface is a blueprint of a class. interface can specify what a class must do, but not how it does it.
• Classes that implement an interface must implement all of the methods defined in the interface except
default methods (JDK 8 onwards).
• We cannot instantiate interface like class.
• Interfaces are designed to support dynamic method resolution at run time.
• Interfaces cannot have constructors.
Defining an Interface: An interface is defined by using the interface keyword.
• Syntax:
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;
}
Implementing Interfaces:
• Once an interface has been defined, one or more classes can implement that interface.
• Implement an interface using implements clause in a class definition, and then create the methods
required by the interface.
• Implements are represented by dashed line arrow (------>).
• Syntax:
class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}

Limitation:
✓ A class can extends only one class.
✓ A class can implements multiple interfaces.
✓ An interface can extend multiple interfaces.
✓ An interface cannot implement another interface or class.

27
22PC1IT201 UNIT - II OOP Through Java

Example: Demonstrate the interface


interface RBI{
void rateOfInterest( );
}
class Axis implements RBI{
@Override
public void rateOfInterest( ) {
System.out.println("Rate of interest in Axis 5%");
}
}
class SBI implements RBI{
public void rateOfInterest( ) {
System.out.println("Rate of interest in SBI 7%");
}
}
public class InterfaceDemo {
public static void main(String args[]){
new Axis( ).rateOfInterest();
new SBI( ).rateOfInterest();
}
}

Output:
Rate of interest in Axis 5%
Rate of interest in SBI 7%

28
22PC1IT201 UNIT - II OOP Through Java

Multiple inheritance with interface


• A class acquiring properties from multiple classes is called multiple inheritance.
• A class can inherit from multiple interfaces, but it can only inherit from one class.
• Java does not support multiple inheritance of classes, but it does support multiple inheritance of
interfaces.
• We can achieve multiple inheritance
1. By implements multiple interfaces to class
2. By extends multiple interfaces to another interface

• Example1: Demonstrate multiple inheritance by implements multiple interfaces to class.


interface Car{
void drive( );
}
interface Bike{
void ride( );
}
public class Person implements Car, Bike {
@Override
public void drive( ) {
System.out.println("Test drive completed by person");
}
@Override
public void ride( ) {
System.out.println("Test ride completed by person");
}
public static void main(String args[]) {
Person obj = new Person ( );
obj.drive();
obj.ride();
}
}
Output:
Test drive completed by person
Test ride completed by person

29
22PC1IT201 UNIT - II OOP Through Java

• Example2: Demonstrate multiple inheritance by extends multiple interfaces to another class.


interface Car{
void drive( );
}
interface Bike{
void ride( );
}
interface Vehicle extends Car, Bike{

}
public class Person implements Vehicle {
@Override
public void drive( ) {
System.out.println("Test drive completed by person");
}
@Override
public void ride( ) {
System.out.println("Test ride completed by person");
}
public static void main(String args[]) {
Person obj = new Person ( );
obj.drive();
obj.ride();
}
}
Output:
Test drive completed by person
Test ride completed by person

30
22PC1IT201 UNIT - II OOP Through Java

Default Interfaces
An interface that contains default method is called default interface.
Default interface methods
• A default method can define a default implementation for an interface method.
• The addition of default methods does not change a key aspect of interface.
• The default methods are by the keyword default.
• Example: Demonstrate default interface method
interface RBI{
default void rateOfInterest( ){
System.out.println("Default Rate of interest is 5%");
}
}
class Axis implements RBI{ //implemented but not override
}
class SBI implements RBI{
@Override
public void rateOfInterest( ) {
System.out.println("Rate of interest in SBI 7%");;
}
}
public class DefaultMerhod {
public static void main(String args[]) { Output:
new Axis().rateOfInterest( ); Default Rate of interest is 5%
new SBI().rateOfInterest( ); Rate of interest in SBI 7%
}
}

Use static methods in an Interface


• 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.
• A static method is called by specifying the interface name, followed by a period, followed by the method
name.
• Syntax: InterfaceName . staticMethodName;

• Example: Demonstrate static method in interface


interface MyInterface {
static int getDefaultNumber( ) { // This is a static interface method.
return 0;
}
Output:
}
Default number is:0
public class static_method_ interface {
public static void main(String args[]) {
System.out.println("Default number is:"+MyInterface.getDefaultNumber( ));
}
}
31
22PC1IT201 UNIT - II OOP Through Java

2-Marks Question
1. Write the advantages of static keyword
2. Differentiate nested and inner class.
3. List and define access modifiers in java.
4. Differentiate private and protected.
5. What is the use of garbage collection? How to implement garbage collection in java?
6. Define varargs and write its syntax.
7. What is lambda expression and write is adavntages.
8. Define inheritance and write the syntax of derive class.
9. Write the advantages of inheritance.
10. What are the uses the super keyword.
11. Differentiate compile time and run time polymorphism.
12. What is dynamic method dispatch.
13. Define method overriding and write its rules.
14. Can we override static method? Justify your answer.
15. Write the uses of final keyword.
16. What is Object class and list some methods.
17. Define abstract method and write its syntax.
18. Define package and write its uses.
19. What are the different ways of importing packages and write its syntax?
20. What are the different ways of finding packages and write its syntax?
21. Define interface and write its uses.
22. Differentiate default interface and default interface method.
23. What is functional interface.
Essay Questions
1. How to use static keyword in JAVA? Explain with examples.
2. Define inheritance. What are the benefits of inheritance? Explain the various forms of inheritance with
suitable code segments.
3. Explain the different forms of polymorphism and explain method overriding with suitable example.
4. Illustrate the use of dynamic method dispatch with example.
5. With suitable code segments illustrate various uses of ‘final’ keyword.
6. Discuss abstract keyword with an example.
7. What is a package? How to create package? Explain with suitable example.
8. Write a short note on package and ways of importing package. Describe with appropriate example.
9. Explain about interface with suitable example.
10. What are the different ways of achieving multiple inheritance? Explain with suitable example.

32

You might also like