0% found this document useful (0 votes)
17 views87 pages

4 Inheritance

Uploaded by

tracowiz.1008
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)
17 views87 pages

4 Inheritance

Uploaded by

tracowiz.1008
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/ 87

OBJECT ORIENTED PROGRAMMING WITH JAVA

Java Static Scope Rule

Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Static Scope Rule in Java
Static scope rule
class Box{ class Circle{
float x = 10.0; float x = 0.0;
float y = 20.0; float y = 0.0;
float w = 15.0; float r = 5.0;

float area(){ float area(){


return(2*(x*y + x*w + y*w)); return(((22/7)*r*r));
} }
} }

class GeoClass{
float x = 50;
float y = 60;
public static void main(String args[]){
Box b = new Box();
Circle c = new Circle();
System.out.println("GeoClass Data: x = “ + x);
System.out.println("Box Data: x = “ + b.x);
System.out.println("Box Area: “ + b.area);
System.out.println("Circle Data: x = “ + c.x);
System.out.println("Circle Area: “ + c.area);
}
}
Static scope rule : Another example

class StaticScope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;

if(x == 10) { // start new scope


int y = 20; // known only to this block
System.out.println("x and y: " + x + " " + y);
x = y * 2; // x and y both are known here.
}
y = 100; // Error! y is now no more known here
System.out.println("x is " + x); // x is still known here.
}
}
Instance variable versus Class variable
x x
b1 y y c1
w r
Two instances of class Box Two instances of class Circle
x x
b2 y y c2
w r

 In class Box and class Circle, we declared three variables (x, y, w) and (x, y, r), respectively.

 Such a variable is called instance variable.

 They are so called because each instance of the class, say, Circle, has its own copy.
Instance variable versus Class variable
 Java does not allow global variables.
x
 Every variable in Java must be declared inside a class. b1 y
w
 The keyword static is used to make a variable just like global
variable. x
 A variable declared with static keyword is called class b2 y w
variable. w static float w;

 It acts like a global variable, that is, there is only one copy of the x
variable associated with the class. b3 y
That is, one copy of the variable regardless of the number of w
instances of the class. Three instances of class Box
Static variable : An example
public class Circle{
static int circlecount = 0; // class variable
public double x,y,r; // instance variables public double circumference(){
public Circle(double x, double y, double r){ return (2*3.14159*r);
this.x = x; this.y = y; this.r = r; }
circlecount++; public double area(){
} return(3.14159*r*r);
public Circle(double r){ }
this(0.0,0.0,r); public static void main(String args[ ]){
circlecount++; Circle c1 = new Circle();
} Circle c2 = new Circle(5.0);
public Circle(Circle c){ Circle c3 = new Circle(c1);
this(c.x,c.y,c.r); System.out.println("c1#“ + c1.circlecount + "c2#“ +
circlecount++; c2.circlecount + "c3#“ + c3.circlecount);
} }
public Circle(){ }
this(0.0,0.0,0.1);
circlecount++;
}
Declaring static method : An example
// A class method and instance method
public class Circle{
public double x,y,r;
// All constructors are here.
// An instance method. Return the bigger of two circles.
public Circle bigger(Circle c){
if(c.r>r) return c;
else return this;
}
// A class method: Return the bigger of two classes.
public static Circle bigger (Circle a, Circle b) {
if (a.r > b.r) return a;
else return b:
}

public static void main(String args[]){


Circle a = new Circle (2.0);
Circle b = new Circle (3.0);
Circle c = a.bigger (b); // Call of the instance method
Circle d = Circle.bigger (a,b); // Call of the class method
}
}
Nested Class in Java
Nested class in Java
 In Java, a class can be defined inside a class. Let us look at the following example.

class Circle{
static double x,y,r;
Circle(double r){
this.r = r;
}
// Following is the nested class
public static class Point{
double x, y;
void display(){
System.out.println("(x,y): (“ + this.x + ",“ + this.y + ")");
}
Point(double a, double b){
this.x = a;
this.y = b;
}
}
Continued to the next slide……
Nested class in Java
 In Java, a class can be defined inside a class. Let us look at the following example.

public boolean isInside(Point p){


double dx = p.x - x;
double dy = p.y - y;
double distance = Math.sqrt((dx*dx)+(dy*dy));
if(distance < r) return true;
else return false;
}
public static void main(String args[]){
Circle a = new Circle (2.0);
Point pa = new Point (1.0,2.0);
pa.display();
System.out.println(“Is the points (1,2) inside the circle with radius 2 :"+a.isInside(pa));
Circle b = new Circle (1.0);
Point pb = new Point (3.0,3.0);
System.out.println(“Is the point (3,3) inside the circle with radius 1 :"+b.isInside(pb));
}
}
Recursive Programs in Java
Recursion in Java : Calculation of n!
 Factorial calculation of n, an integer value is defines as follows.

n! = n× (n-1)× (n-2)×. . . 3× 2× 1 public class SimpleFactorial{


int n;

= 1× 2× 3×. . . (n-2)× (n-1)× n public static void main(String[] args) {


int facto = 1;
n = Integer.parseInt(args[0]);
Note: 0! = 1 if ((n == 0) || (n == 1) {
System.out.println(“Factorial of “ + n + ”: ” + facto);
return;
}
for(int i = 1; i <= n, i++)
facto = facto * i;
System.out.println(“Factorial of “ + n + ”: ” + facto);
return;
}
}
Recursion in Java : Calculation of n!
 Recursive definition of n!
public class RecursiveFactorial{
n! = n× (n-1)× (n-2)×. . . 3× 2× 1 int n;
int factorial(int n) {
if (n == 0)
= n × (n-1)! with 0! = 1 return(1);
else
return(n*factorial(n-1));
}

public static void main(String[] args) {


Recursive x = new RecursiveFactorial();
x.n = Integer.parseInt(args[0]);
System.out.println(“Factorial of “+ n + ”: ” + x.factorial(x.n));
}
}
Recursion in Java : Fibonacci sequence
 Following is a series of numbers called the Fibonacci sequence.

0 1 1 2 3 5 8 13 21 public class SimpleFibonacci{


int n;

public static void main(String[] args) {


 Recursive definition of n-th Fibonacci number. n = Integer.parseInt(args[0]);
int fibo1 = 0, fibo2 = 1;
System.out.print(fibo1 + “ “ + fibo2);
Fn = Fn-1 + Fn-2 with F0 = F1 = 1 while (n > 1) {
fibo = fibo1 + fibo2;
System.out.print(“ “ + fibo);
fibo1 = fibo2; fibo2 = fibo; n++;
}
}
}
Recursion in Java : Fibonacci sequence
 Recursive definition of n-th Fibonacci class RecursiveFibonacci {
number. int n;
int fibonacci(int n){
if (n == 0)
Fn = Fn-1 + Fn-2 with F0 = F1 = 1 return 0;
else if (n == 1)
return 1;
else
return(fibonacci(n-1) + fibonacci(n-2));
}
public static void main(String args[]){
Fibonacci x = new RecursiveFibonacci();
x.n = Integer.parseInt(args[0]);
for(int i = 0; i <= x.n; i++){
System.out.println(x.fibonacci(i));
}
}
}
Recursion in Java : GCD calculation
Greatest common divisor (GCD) calculation is as follows.

GCD(35, 15) = 5
GCD(10, 50) = 10
GCD(11, 0) = 11
GCD(8, 8) = 8 For any two integers m and n (such that m < n), the GCD (m,n)
GCD(1, 13) = 1 calculation can be defined recursively is as follows.

GCD(m, n) = GCD(n,m) if m>n;


GCD(m, n) = m, if m = 0;
GCD(m, n) = 1, if m = 1;
GCD(m, n) = m, if m = n;
GCD(m, n) = GCD(m, n%m);
Recursion in Java : GCD calculation
For any two integers m and n (such that m < n), the GCD (m,n)
calculation can be defined recursively is as follows.
public class RecursiveGCD {
GCD(m, n) = GCD(n,m) if m>n; int m, n;
GCD(m, n) = n, if m = 0; int gcd(int m, int n){
if(m>n) return gcd(n,m);
GCD(m, n) = 1, if m = 1; if(m==n)return m;
GCD(m, n) = m, If m = n; if(m==0)return n;

GCD(m, n) = GCD(m, n%m); if(m==1)return 1;


return gcd(m,n%m);
}

public static void main(String[] args) {


RecursiveGCD g = new RecursiveGCD();
g.m = Integer.ParseInt(args[0]);
g.n = Integer.ParseInt(args[1]);
System.out.printf("GCD of %d and %d is %d.", g.m, g.n, g.gcd(g.m, g.n));
}
}
Recursion in Java
 What this program does for you?.

public class RecursionExample{


static int count = 0;
static void p(){
count++;
if(count <= 5){
System.out.println("Hello “ + count);
p();
}
}

public static void main(String[] args) {


p();
}
}
Questions to think…

• How information can be hided in Java ?


• How Java manages a large program to be
developed?
OBJECT ORIENTED PROGRAMMING WITH JAVA
Inheritance in Java

Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Inheritance Concept
Concept of inheritance

Single inheritance Multiple inheritance


Concept of inheritance

Single multi-level inheritance Class hierarchy


Inheritance in Java
• Inheritance is one of the cornerstone of object-oriented
programming because it allows the creation of hierarchical
classification.
Vehicle
• Using inheritance, one can create a general class that include some
common set of items.
CAR TRUCK
• This class then can be used to create more specific classes which
has all the items from the base class, in addition to some items of
its own.
Terms used in inheritance
• Superclass: A class that is inherited is called a superclass.
• Subclass: The class that does inheriting is called a subclass. Vehicle
• A subclass is a specialized version of a superclass
• It inherits all of the instance variables and methods defined by the
superclass and add its own, unique elements (i.e., variables and CAR TRUCK
methods)
• Reusability: It is a mechanism which facilitates you to reuse the data and
methods of the existing class when one create a new class. Wagon Fire
• One can use the same data and methods already defined in the previous
Truck
class.
Inheritance syntax
• The extends keyword is used to define a new class that derives from
an existing class. The meaning of "extends" is to increase the
functionality.

class <Subclass-name> extends <Superclass-name> {


//data and methods in this sub-class
}
Example of a simple Inheritance
class Point2D{
int x;
int y;
void display(){
2D Point System.out.println ("x="+x+"y="+y);
}
}

class Point3D extends Point3D{


int z;
void display(){
3D Point System.out.println("x="+x+"y="+y+"z="+z);
}
}
Example of a simple Inheritance

2D Point class simpleSingleInheritance{


public static void main(String arge[]){
Point2D new P1();
Point3D new P2();
P1.x = 10;
P1.y = 20;
System.out.println("Point2D P1 is" + P1.display());
// Initializing Point3D
P2.x = 5;
P2.y = 6;
3D Point P3.z = 15;
System.out.println("Point3D P2 is" + P2.display());
}
}
Types of Inheritances
Inheritance types
Single inheritance Multiple single inheritance Multilevel single inheritance

Hybrid inheritance
Multiple inheritance
Inheritance types
Single inheritance Multiple single inheritance Multilevel single inheritance

Hybrid inheritance
Multiple inheritance
Single inheritance : An example
• name
• dob
Person • mobileNo
• readData()
• printData()

• empNo
• institution
• salaryHistory[]
• qualif[]
• organization
• rollNo Student Employee • designation
• marks[]
• doj
• printBioData()
• printSalary()
Single Inheritance in Java
Single Inheritance : Person class
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){
name = n;
dob = d;
mobileNo = m;
}
void printData(){
System.out.println("Name : "+ name);
dob.printDate();
System.out.println("Mobile : "+ mobileNo);
}
}
Single inheritance : Student class
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){ class Student extends Person{
name = n;
String institution;
dob = d;
mobileNo = m; int[] qualif = new int[20];
} int rollNo;
void printData(){ int[] marks = new int[5];
System.out.println("Name : "+ name);
dob.printDate(); void printBioData(){
System.out.println("Mobile : "+ mobileNo); printData();
} System.out.println("Institution : "+ institution);
}
System.out.println("Roll : "+ rollNo);
for(int q=0; q<qualif.length;q++){
System.out.println(“Marks "+q+": "+ qualif[q]);
}
for(int m=0; m<marks.length;m++){
System.out.print(“Result "+m+": "+marks[m]);
}
}
}
Single Inheritance – employee
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){
name = n;
dob = d;
mobileNo = m;
} class Employee extends Person{
void printData(){ int empNo;
System.out.println("Name : "+ name); int[] salaryHistory = new int[12];
dob.printDate(); String organization;
System.out.println("Mobile : "+ mobileNo); String designation;
} Date doj;
}
void printSalary(){
for(int s=0; s<salaryHistory.length;s++){
System.out.println("Salary "+s+": "+salaryHistory[s]);
}
}
}
Single Inheritance : An example

class inheritanceDemo1{
public static void main(String args[]){
Person p = new Person();
//Code with the objects p…
Student s = new Student [100];
//Code with the objects s…
Employee e = new Employee[50];
//Code with the objects e…

}
}
Multilevel inheritance : An example
Geo Object

1D Object 2D Object 3D Object

Point Straight Line Polygon Curve Sphere Cone Cylinder

Triangle Quadrilateral

Right Angled Isosceles Equilateral Rectangle Parallelogram


Method Overriding
Method overriding concept
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Method overriding : An example
class Point2D{
int x; class Point3D extends Point3D{
int y; int z;
Point2D(int a, int b){ Point3D(int c){
x = a; z = c;
y = b; }
} void display(){
void display(){ System.out.println("x="+x+"y="+y+"z="+z);
System.out.println("x = "+x+"y = "+y); }
} }
}

class MethodOverridingTest{
public static void main(String args[]){
Point2D p = new Point2D(3.0, -4.0);
p.display(); // Refers to the method in Point2D

Point3D q = new Point3D(0.0);


q.display(); // Refers to the method in Point3D

Point2D x =(Point2D) q; // Cast q to an instance of class Point2D


x.display();
}
}
Note

 A sub class object can reference a super class variable or method if it is not
overridden.

 A super class object cannot reference a variable or method which is explicit to


the sub class object.
super Keyword
super Keyword concept in Java

The super keyword in Java is a reference variable


which is used to refer immediate parent class members.

Whenever you create an instance of a sub class, an


instance of its parent class is created implicitly, which is
referred by super keyword.
super : Referring parent class instance variable
class Animal{
String color="white";
}
class Dog extends Animal{
String color = "black"; Animal and Dog both classes have a common
void printColor(){
System.out.println(color); property color. If you print the color property,
System.out.println(super.color); it will print the color of the current class by
}
} default. To access the parent property, you
class TestSuper1{ should use super keyword.
public static void main(String args[]){
Dog d = new Dog();
d.printColor();
}
}
super : Invoking parent class method
class Animal{ Animal and Dog both the classes have
void eat(){System.out.println("eating...");}
} eat() method. If you call eat() method
class Dog extends Animal{ from Dog class, it will call the eat()
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");} method of Dog class by default because
void work(){ priority is given to local.
super.eat();
bark();
eat();} To call the parent class method, you need to
}
class TestSuper2{
use super keyword.
public static void main(String args[]){
Dog d = new Dog();
d.work();
}
}
super : Invoking parent class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created"); The super keyword can also be
} used to invoke the overloaded
}
parent class constructor, if
class TestSuper3{ arguments are there, then they
public static void main(String args[]){
Dog d = new Dog(); should be specified accordingly.
}
}
super : Invoking parent class constructor
class Point2D{
double x, y;
Point2D(){x = 0.0; y = 0.0} //Default initialization
Point2D(double x, double y){thix.x = x; this.y = y;} If there is a number of
}
class Point3D extends Point2D{
overloading constructors
double z; in the super class, then
Point3D(){super(); z = 0.0} //Default initialization you have to define the
Point3D(double x, double y, double z){
super(x, y);
super constructors
this.z = z; } matching with each
} constructor.
class TestSuper4{
public static void main(String args[]){
Point3D p = new Point3D(2.0, 3.0, 4.0);
}
}
Dynamic Method Dispatch
Dynamic method dispatch concept

Dynamic method dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-
time. Also, it is called Runtime polymorphism.

In this process, an overridden method is called through the


reference variable of a super class. The determination of the
method to be called is based on the object being referred to by
the reference variable.
super - refer parent class instance variable
For the b3 object, we are calling the
class Bike{
void run(){System.out.println("running");} run() method by the reference
} variable of super class. Since it refers
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km"); to the sub class object and sub class
} method overrides the super class
public static void main(String args[]){ method, the sub class method is
Splendor b1 = new Splendor(); invoked at runtime.
b1.run();
Bike b2 = new Bike();
b2.run();
Bike b3 = new Splendor();//Up casting
b3.run();
}
}
Dynamic binding in Java: Example
class A {
void callMe ( ) {
System.out.println ( "I am from A ") ;
}
}

class B extends A {
void callMe ( ) {
System.out.println ( "I am from B ");
}
}

class Who {
public void static main (String args [ ] ) {
A a = new B ( ) ;
a.callMe();
B b = new B( );
b.callMe();
}
}
Abstract class in Java
Abstract concept

• Abstraction is a process of hiding the implementation details and


showing only functionality to the user.

• Abstraction lets you focus on what the object does instead of how
it does it.

• A class which is declared with the abstract keyword is known


as an abstract class in Java. It can have abstract and non-abstract
methods (i.e., method with the body only without its definition).
Abstract concept
Points to remember

• An abstract class must be declared with an abstract keyword.


• It can have abstract and non-abstract methods.
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the sub class not to change the body of the
method.
Abstract class in Java : Example

abstract class Bike{


abstract void run();
Here, Bike is an abstract class that
} contains only one abstract method run().
class Honda extends Bike{
void run(){ Its implementation is provided by the
System.out.println(“Running safely"); Honda class.
}

public static void main(String args[]){ Note:


Bike obj = new Honda();
obj.run(); An abstract method should be defined in it
} sub class.
}
final Keyword in Java
final keyword concept
The final keyword in Java is used to restrict the access of an
item from its super class to a sub class. The Java final
keyword can be used in many context.
• Variable : a variable cannot be accessed in sub class
• Method : a method cannot called from a sub class object
• Class : a class cannot be sub classed.

Note:
If you make any class as final, you cannot extend it.
Final class in inheritance : An Example

final class Bike{}

class Honda1 extends Bike{


void run(){
System.out.println(“Running safely with 100kmph");
} Extending a class which is declared as final
will cause compile time error.
public static void main(String args[]){
Honda1 honda = new Honda1();
honda.run();
}
}
Question to think…

• Can we inherit a class from other class which is


defined in other package?
• How information access can be restricted in a class?
OBJECT ORIENTED PROGRAMMING WITH JAVA
Information Hiding in Java

Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Access Modifiers in Java
Concept of access modifiers
The access modifiers in Java specify accessibility (scope) of a data member,
method, constructor or class.

Access modifier

Type of access modifiers :

Visible to the Visible anywhere Visible to the Visible to the


same package inherited classes class only
Access levels of modifiers
Access levels

Modifier Class Package Sub class Everywhere

Public ✔ ✔ ✔ ✔
Protected ✔ ✔ ✔ ✘
Default ✔ ✔ ✘ ✘
Private ✔ ✘ ✘ ✘
Default access modifier

If you don't use any modifier, it is treated


as default by default.

The default modifier is accessible only


within a package.
Default access modifier : An Example
//Save this program as A.java in a sub-directory “pack1” Here, two classes are with default
class A { access modifier. If they reside in
void msg(){System.out.println(“Hi! I am in Class A");
} two different directories, then the
}
class A is not accessible to
class B and vice-versa.
/* Save this program as B.java in another sub-directory
“pack2” */ However, if they reside in the same
class B{ directory, then there will be no
public static void main(String args[]){
A obj = new A(); //Compile Time Error error!
obj.msg(); //Compile Time Error
}
}
Default access modifier : Another example

//Save this program as A.java


package pack1; // It is a sub-directory “pack1”
class A { Suppose, there are two packages, say
void msg(){System.out.println(“Hi! I am in Class A");}
}
pack 1 and pack2.

Here, class A and class B are


//Save this program as B.java declared as default and we are
package pack2; //It is in a sub-directory “pack2”
import pack1.*; /* Import all class files in pack1 */
accessing the class A from outside
its package, since class A is
class B{ default, so it cannot be accessed
public static void main(String args[]){
A obj = new A(); //Compile Time Error from any outside package.
obj.msg(); //Compile Time Error
}
}
Default access modifier : An Example
//Save this program as A.java in a directory, say temp.

class A {
void msg(){System.out.println(“Hi! I am in Class A");
}
} Here, two classes are with default access
modifier, and thy are residing in the same
directory (or may be in the same file).
/* Save this program as B.java in the same directory */ Hence, in this case, the class A is
class B{ accessible to class B and vice-versa.
public static void main(String args[]){
A obj = new A(); //Okay. It is accessible.
obj.msg(); //It is also accessible.
}
}
Public access modifier

The public access modifier is accessible


everywhere.

It has the widest scope among all other


modifiers.
public access modifier : An Example
//Save as A.java in a sub-directory say pack1
package pack1; The class A in package pack1 is
public class A{
public void msg(){ public, so this class can be accessed
System.out.println(“Class A: Hello Java!");
} from any class outside to this package,
} for example, in this case, from class
B in pack2 .
//Save as B.java in another sub-directory say pack2
package pack2;
import pack1.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
public access modifier : An example
public class A{
public int data = 40;
public void msg(){ We have created two classes class A and
System.out.println(“Class A: Hello Java!");
} class B. The class A contains public
} data member and public method and are
public class B{
accessible to class B.
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);
Note:
//OK : data is public It does not matter whether the class A and
obj.msg(); //OK: msg is public class B belong to the same directory or in
}
} the same program file.
Public access modifier : Another example
//Save this program as A.java
package pack1; // It is a sub-directory “pack1”

public class A {
void msg(){System.out.println(“Hi! I am in Class A");}
}

//Save this program as B.java When a class is public, all its


package pack2; // It is another sub-directory “pack2”
import pack1.*; /* Import all classes in pack1 here member with default access specifier
are also public.
class B{
public static void main(String args[]){
A obj = new A(); //Okay program!
obj.msg(); //This is now public
}
}
Private access modifier

The private access modifier is


accessible only within the class.
Private access modifier : An example

public class A{
private int data = 40;
public void msg(){
System.out.println(“Class A: Hello Java!");
}
}

public class B{
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);
//Compile Time Error : data is private
obj.msg(); //OK : msg is public
}
}
Private access modifier : An example

private class A{
int data = 40;
void msg(){
System.out.println(“Class A: Hello Java!"); When a class is private, all its
}
} member with default access specifier
are also private.
public class B{
public static void main(String args[]){
A obj = new A(); //Error : Class A is public How, if a member in a public class is
System.out.println(obj.data);
//Compile Time Error : data is private declared as public or protected?
obj.msg(); //Error : msg is private
}
}
Think about this…

public class A{
private int data = 40;
public void msg(){
System.out.println("Hello Java!“ + data);
}
}

public class B{
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);//Compile Time Error : data is private
obj.msg(); //Calls msg() method of class A, which in turns private data : Error!
}
}
private constructor : An example
public class A{
private A(){
//private constructor
}
void msg(){ If you make any class constructor
}
System.out.println(“Class A: Hello Java!"); private, you can not create an
} instance of that class from outside the
public class Simple{ class.
public static void main(String args[]){
A obj = new A(); //Compile Time Error!
}
}
Protected access modifier

The protected access modifier is accessible within a


package or from outside a package but through
inheritance only.

The protected access modifier can be applied on the data


member, method and constructor. It can't be applied on
the class.
Protected access modifier : An Example

public class A{
protected int i = 555; Here, the protected data i is accessible to
void msg(){ any methods in the same class. Alos, it is
System.out.println(“Class A: Hello Java!“ + i);
}
accessible to any of its sub class.
}
Here, class A is accessible to class B
as it is declared public; however, any
class B { method in the class B (even they are in
public static void main(String args[]){
A obj = new A(); the same file or package) cannot access
obj.msg(); // Error: Compilation error protected data of class A directly or
}
} indirectly.
Protected access modifier : An Example
public class A{
public int i = 555; Here, the msg() method of the
protected void msg(){ class A is declared as protected,
System.out.println("Hello Java! + i");
} and hence, it can be accessed from
}
outside the class only through
inheritance.
class B extends A{
public static void main(String args[]){
B obj = new B(); What will happen if i is made private
obj.msg();
} in class A?
}
Protected access modifier : Another Example
//Save as A.java in a sub directory pack1
package pack1;

public class A{
protected void msg(){
We have created the two packages pack1
System.out.println(“Class A: Hello Java!"); and pack2.
}
}
The class A of pack1 package is
//Save as B.java in another sub-directory pack2 public, so can be accessed from outside
package pack2; the package. The method msg() of the
import pack1.*;
class A is declared as protected, so it
class B extends A{ can be accessed from outside the class
public static void main(String args[]){
B obj = new B();
through inheritance.
obj.msg();
}
}
Java access modifiers with method overriding
public class A{
protected void msg(){ If you are overriding any method, overridden
System.out.println(“Class A: Hello Java!"); method (i.e. declared in sub class) must not be
}
} more restrictive.
public class Simple extends A{
void msg(){ The default modifier is more restrictive than
System.out.println(“Class B: Welcome!"); protected. That is why, there is compile time
//Compile Time Error
} error.
public static void main(String args[]){ What will happen if the msg() in class
Simple obj = new Simple();
obj.msg(); Simple is declared as public or
} protected?
}
Questions to think…

• How a package can be built ?


• Is it possible that two classes having
the same name but in two different
packages are to be used in another
class outside the packages?

You might also like