0% found this document useful (0 votes)
9 views36 pages

7-Access Specifiers, Packages

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 36

Contents

 Method Overriding

 Access Specifiers

 Packages
Method Overriding
If subclass has the same method as declared in parent class, it is method overriding.

Usage:
•to provide specific implementation of a method that is already provided by its super class.
•used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Example 1: Class Vehicle{
void run() {
System.out.println("Vehicle is running"); } }

class Scooty extends Vehicle{


void run() { System.out.println(“Scooty is running safely"); }
public static void main(String args[])
{ Scooty obj = new Scooty();
obj.run(); }
Example 2:
class Bank{
int getROI() { return 0; } }

class SBI extends Bank{


int getROI() { return 8; } }

class ICICI extends Bank{


int getROI() { return 7; } }

class AXIS extends Bank{


int getROI() { return 9; } }

class Test2{
public static void main(String args[]) {
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getROI());
System.out.println("ICICI Rate of Interest: "+i.getROI());
System.out.println("AXIS Rate of Interest: "+a.getROI());
}}
this keyword
6 usage of java this keyword:

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
class Student{ int rollno; String name; float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno; this.name=name; this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{ Output:
public static void main(String args[]){ 111 ankit 5000
Student s1=new Student(111,"ankit",5000f); 112 sumit 6000
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
super keyword

It is a reference variable which is used to refer immediate parent class object.


Whenever we create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of super Keyword:

1. to refer immediate parent class instance variable.


2. to invoke immediate parent class method.
3. to invoke immediate parent class constructor.
super is used to refer immediate parent class instance variable:

class Animal{
String color="white";
}
class Dog extends Animal{ String color="black"; Output:
void printColor(){ System.out.println(color);//prints color of Dog class black
System.out.println(super.color);//prints color of Animal class white
}
}
class TestSuper1{
public static void main(String args[]){ Dog d=new Dog();

d.printColor();
}}
Final Keyword

- It is used to denote constants.


- It can be used with variables, methods, and classes.

Once any entity (variable, method or class) is declared final, it can be assigned only once.
That is,

•the final variable cannot be reinitialized with another value


•the final method cannot be overridden
•the final class cannot be extended
(1) final Variable

we cannot change the value of a final variable. For example:

class FinalVar {
• created a final variable named age.
public static void main(String[] args) {
• tried to change the value of the final variable.
• On execution, a compilation error with the
// create a final variable
final int AGE = 32; following message appeared,

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}

Note: It is recommended to use uppercase to declare final variables in Java.


(2) final Method
final method cannot be overridden by the child class. For example,
class FinalDemo {
// create a final method - created a final method named display() inside the
FinalDemo class.
public final void display() { - Here, the Main class inherits the FinalDemo class.
System.out.println("This is a final
method."); } } - tried to override the final method in the Main class.
- On execution of the program, we will get a
compilation error with the following message:
class Main extends FinalDemo {
// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
} }
(3) final Class
the final class cannot be inherited by another class. For example:
// create a final class
final class FinalClass {
- created a final class named FinalClass.
public void display() {
- Tried to inherit the final class by Main class.
System.out.println("This is a final method.");
} } On executing the program:
get a compilation error with the following message:
// try to extend the final class
class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display(); } }
Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a
way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++.


But, in java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

• It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
• It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
gc() method
used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.

public static void gc(){}

Example: public 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; object is garbage collected
System.gc(); object is garbage collected
}}
Package
• A package is a group of similar types of classes, interfaces and sub-packages.
• Types of packages:

• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package


1) used to categorize the classes and interfaces so that they can be easily maintained.
2) provides access protection.
3) removes naming collision.
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for GUI (like button , menus etc).
6) java.net: Contain classes for supporting networking operations.
How to Create a package?
• Choose the name of the package. Include the package command as the first line of code in Source File.
• The Source file contains the classes, interfaces, etc you want to include in the package. Compile to create
the Java packages

- To compile with package statements, use -d option as :


javac -d Destination_folder file_name.java OR
javac –d . filename.java ( forces the compiler to create a package;
the "." operator represents the current working directory)

A folder with the given package name is created in the specified destination, & the compiled class files will be placed in
that folder.

The -d switch specifies the destination where to put the generated class file. You can use any directory name like
d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).
Additional points about package:

• Package statement must be first statement in the program even before the import statement.
• A package is always defined as a separate folder having the same name as the package name.
• Store all the classes in that package folder.
• All classes of the package which we wish to access outside the package must be declared public.
• All classes within the package must have the package statement as its first line.
• All classes of the package must be compiled before use.
package mypack;
How to compile java package public class Simple
{
syntax :
public static void main(String args[])
javac -d directory javafilename { System.out.println("Welcome to package");
}
How to run java package program }
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
user-defined packages:
Examples: • created a class Calculator inside a package name letmecalculate.
• declare the package name in the first statement of program.
• A class can have only one package declaration.
• Calculator.java file created inside a package letmecalculate

package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
to use this package in another program:

import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}

• To use the class Calculator, import the package letmecalculate, as:


import letmecalculate.Calculator. This only imports the Calculator class.
• If there are several classes inside package letmecalculate then import the package as:
import letmecalculate.*;
To access package from another package:

There are three ways to access the package from outside the package :

a)import package.*;
b)import package.classname;
c)fully qualified name.
1) Using packagename.* : all classes and interfaces of this package are accessible but not subpackages.
The import k/w is used to make classes & interface of another package accessible to current package.

//save by A.java
package pack; Example:
public class A {
public void msg() {
Output: Hello! I
System.out.println("Hello! I am from class A, package pack"); } }
am from class A,
//save by B.java package pack
package mypack;
import pack.*;

class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
} }
2) Using packagename.classname: only declared class of this package will be
accessible.
Example:
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello ! I am from class A, package pack"); } }
Output: Hello! I
//save by B.java am from class A,
package mypack; package pack
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
3) Using fully qualified name
Only declared class of this package will be accessible. Now, import is not required.
Needed to use fully qualified name every time the class or interface are accessed.
- generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example: //save by A.java
package pack;
public class A {
public void msg() {
System.out.println(("Hello ! I am from class A, package pack");
} }
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
} }
Subpackage in java
• Package inside the package is called the subpackage.
• Created to categorize the package further.
- On import of a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages.
Hence, needed to import the subpackage as well.

For example :
If I create a package inside letmecalculate package then that will be called sub package.
Lets say I have created another package inside letmecalculate and the sub package name is multiply.
So if I create a class in this subpackage it should have this package declaration in the beginning:
package letmecalculate.multiply;
// Save as Multiplication.java

package letmecalculate.multiply; Now if I need to use this Multiplication class I have to


public class Multiplication { either import the package like this:
int product(int a, int b){
return a*b;
} }
import letmecalculate.multiply;
or I can use fully qualified name like this:

letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();
Points to remember:
1. Sometimes class name conflict may occur. For example: Lets say we have two
packages abcpackage and xyzpackage and both the packages have a class with the
same name, let it be JavaExample.java. Now suppose a class import both these
packages like this:

import abcpackage.*;
import xyzpackage.*;
This will throw compilation error. To avoid such errors you need to use the fully
qualified name method that I have shown above. For example

abcpackage.JavaExample obj = new abcpackage.JavaExample();


xyzpackage.JavaExample obj2 = new xyzpackage.JavaExample();
2) If we create a class inside a package while importing another package then the
package declaration should be the first statement, followed by package import.
For example:

package abcpackage;
import xyzpackage.*;

3. A class can have only one package declaration but it can have more than one package
import statements. For example:

package abcpackage; //This should be one


import xyzpackage;
import anotherpackage;
import anything;
4. The wild card import like package.* should be used carefully when working with subpackages.
For example: package abc have another package todo. Now todo is a subpackage.

classes inside abc are: Example1, Example 2, Example 3


classes inside todo are: Demo1, Demo2

So , on importing the package abc using wildcard like this: import abc.*;
will only import classes Example1, Example2 and Example3 but it not import the classes of sub package.

To import the classes of subpackage, import like this: import abc.todo.*;


This will import Demo1 and Demo2 but it will not import the Example1, Example2 and Example3.

So to import all the classes present in package and subpackage, use two import statements like this:

import abc.*;
import abc.todo.*;
Access Control
Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers: specifies accessibility (scope) of a data member, method,
constructor or class.

There are 4 types of java access modifiers

1. private
2. default
3. protected
4. public
(a) private access modifier
Its accessible only within class.

Example: created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so
there is compile time error.
class A{
private int data=40;
private void msg()
{System.out.println("Hello java");} }

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}
(b) default access modifier
If you don't use any modifier, it is treated as default by default.
Its accessible only within package.
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 can’t be accessed from outside package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");} } As the scope of class A and its method msg() is
default so it cannot be accessed from outside
//save by B.java the package.
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error } }
(c) protected access modifier
Its accessible within package and outside the package but through inheritance only.
Can be applied on the data member, method and constructor. It can't be applied on the class.
Example: we have created the two packages pack and mypack. The A class of pack package is public, so can be
accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B(); Output:Hello
obj.msg();
}}
(d) public access modifier
Its accessible everywhere. It has the widest scope among all other modifiers.
Example:
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");} }
//save by B.java Output:Hello
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}}
Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be
more restrictive.

class A{
protected void msg(){System.out.println("Hello java");} }

public class Simple extends A{


void msg(){System.out.println("Hello java");} //C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
} }

The default modifier is more restrictive than protected. Thus, there is a compile-time error.
the access modifiers by a simple table:

Member access and Inheritance


• A subclass includes all members of its super class but can’t access its private declared members.
• Attempt to access a private variable would cause compilation error as it causes access violation.
• The variables declared as private, is only accessible by other members of its own class.
• Subclass have no access to it.

You might also like