Anda di halaman 1dari 48

ACCESS MODIFIERS IN JAVA

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:


Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
Understanding Java Access Modifiers
Private
 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
 }
 }
Role of Private Constructor

 If you make any class constructor private, you cannot create the
instance of that class from outside the class. For example:
 class A{
 private A(){}//private constructor
 void msg(){System.out.println("Hello java");}
 }
 public class Simple{
 public static void main(String args[]){
 A obj=new A();//Compile Time Error
 }
 }
Default
 //save by A.java
 package pack;
 class A{ In this example, we have
 void msg(){System.out.println("Hello"); created two packages pack
}
 }
and mypack. We are
accessing the A class from
 //save by B.java outside its package, since A

 package mypack; class is not public, so it
 import pack.*; cannot be accessed from
 class B{
 public static void main(String args[]){ outside the package.
 A obj = new A();//Compile Time Error

 obj.msg();//Compile Time Error


 }
 }
Protected
 //save by A.java
 package pack; we have created the two
 public class A{
 protected void msg(
packages pack and mypack.
 {System.out.println("Hello");} The A class of pack package
 } is public, so can be
accessed from outside the

 //save by B.java package. But msg method
 package mypack; of this package is declared
 import pack.*;

as protected, so it can be
 class B extends A{ accessed from outside the
 public static void main(String args[]){ class only through
 B obj = new B();
 obj.msg();
inheritance.
 }
 }
Protected
 //save by A.java
 package pack; we have created the two
 public class A{
 protected void msg(
packages pack and mypack.
 {System.out.println("Hello");} The A class of pack package
 } is public, so can be
accessed from outside the

 //save by B.java package. But msg method
 package mypack; of this package is declared
 import pack.*;

as protected, so it can be
 class B extends A{ accessed from outside the
 public static void main(String args[]){ class only through
 B obj = new B();
 obj.msg();
inheritance.
 }
 }
Public
 //save by A.java
 package pack;
 public class A{ The public access modifier
 public void msg(){System.out.println("H is accessible everywhere. It
ello");}
 } has the widest scope
 among all other modifiers.
 //save by B.java

 package mypack;
 import pack.*;
 class B
 {
 public static void main(String args[])
 {
 A obj = new A();
 obj.msg();
 }
 }
Inheritance in Java

 Inheritance in Java is a mechanism in which one object


acquires all the properties and behaviors of a parent
object.

 The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new
methods and fields in your current class also
Why use inheritance in java

 For Method Overriding


 (so runtime polymorphism can be achieved).

 For Code Reusability.

The syntax of Java Inheritance


 class Subclass-name extends Superclass-name
 {
 //methods and fields
 }
 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.
Java Inheritance Example

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.
 class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Types of inheritance in java

 On the basis of class, there can be three types of


inheritance in java: single, multilevel and
hierarchical.
 In java programming, multiple and hybrid
inheritance is supported through interface only.
Multiple inheritance is not supported in Java through class.
Not supported inheritance in java
Single Inheritance Example
 class Animal{
 void eat(){System.out.println("eating...");}
 }
 class Dog extends Animal{
 void bark(){System.out.println("barking...");}
 }
 class TestInheritance{
 public static void main(String args[]){
 Dog d=new Dog();
 d.bark();
 d.eat();
 }}
Multilevel Inheritance Example

 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();
 }}
Hierarchical Inheritance Example

 class Animal{
 void eat(){System.out.println("eating...");}
 }
 class Dog extends Animal{
 void bark(){System.out.println("barking...");}
 }
 class Cat extends Animal{
 void meow(){System.out.println("meowing...");}
 }
 class TestInheritance3{
 public static void main(String args[]){
 Cat c=new Cat();
 c.meow();
 c.eat();
 //c.bark();//C.T.Error
 }}
Why multiple inheritance is not supported in java?

 To reduce the complexity and simplify the language, multiple


inheritance is not supported in java.
 Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method
and you call it from child class object, there will be ambiguity to call
the method of A or B class.
 Since compile-time errors are better than runtime errors, Java
renders compile-time error if you inherit 2 classes. So whether you
have same method or different, there will be compile time error.
Program
 class A{
 void msg(){System.out.println("Hello");}
 }
 class B{
 void msg(){System.out.println("Welcome");}
 }
 class C extends A,B{//suppose if it were

 public static void main(String args[]){


 C obj=new C();
 obj.msg();//Now which msg() method would be invoked?
 }
 }
Interface in Java
 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.

 In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.
Why use Java interface?
There are mainly two reasons to use interface. They
are given below.
i. It is used to achieve abstraction.
ii. By interface, we can support the functionality of
multiple inheritance.
iii.
How to declare an interface?

 An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the
empty body, and all the fields are public, static and final by default. A
class that implements an interface must implement all the methods declared
in the interface.
Syntax
 Interface <interface_name>

 {


 // declare constant fields
 // declare methods that abstract
 // by default.
 }
Internal addition by the compiler

In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.
The relationship between classes and interfaces
Java Interface Example
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();
}
}
Java Interface Example: Bank

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple inheritance in Java by interface

 If a class implements multiple interfaces, or


an interface extends multiple interfaces, it
is known as multiple inheritance.


Program of Multiple inheritance

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Multiple inheritance is not supported through class in
java, but it is possible by an interface, why?

 Multiple inheritance is not supported in the


case of class because of ambiguity.
However, it is supported in case of an
interface because there is no ambiguity. It
is because its implementation is provided
by the implementation class. For example:
Interface inheritance
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable{


public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Java 8 Default Method in Interface

 interface Drawable{  Since Java 8, we


 void draw(); can have method
 default void body in interface.
msg(){System.out.p But we need to
rintln("default make it default
method");} method.
 } 

 class Rectangle
implements
Drawable{
Nested Interface in Java

 Interface printable{
 void print();
 interface MessagePrintable{
 void msg();
 }
 }
program
 interface Showable{
 void show();
 interface Message{
 void msg();
 }
 }
 class TestNestedInterface1 implements Showable.Message{
 public void msg(){System.out.println("Hello nested interface");}

 public static void main(String args[]){
 Showable.Message message=new TestNestedInterface1();//upcasting here
 message.msg();
 }
 }
Abstract class in Java

 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 (method with the body).

 Abstract class in Java


 A class which is declared as abstract is known as
an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method
implemented. It cannot be instantiated.
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 subclass
not to change the body of the method.
Example of abstract class
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely");}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Understanding the real scenario of Abstract class
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape
{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}
Abstract class having constructor, data member and methods

//Example of an abstract class that has abstract and non-abstract methods


abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods class
TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Rule:
If there is an abstract  class Bike12
method in a class,  {
that class must be  abstract void run();
abstract.  }
Difference between abstract class and interface
Super Keyword in Java
 The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
 Whenever you create the instance of subclass, an instance of parent class is

created implicitly which is referred by super reference variable.


Usage of Java super Keyword
 super can be used to refer immediate parent class instance variable.

 super can be used to invoke immediate parent class method.

 super() can be used to invoke immediate parent class constructor.


super is used to refer immediate parent class instance variable.

 We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.
 class Animal{
 String color="white";
 }
 class Dog extends Animal{
 String color="black";
 void printColor(){
 System.out.println(color);//prints color of Dog class
 System.out.println(super.color);//prints color of Animal class
 }
 }
 class TestSuper1{
 public static void main(String args[]){
 Dog d=new Dog();
 d.printColor();
 }}
super can be used to invoke parent class method

 The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is used
if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
super is used to invoke parent class constructor.

 The super keyword can also be used to invoke the parent class constructor. Let's see
a simple example:

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
super() is added in each class constructor automatically by
compiler if there is no super() or this().
Another example of super keyword where super() is provided by the compiler
implicitly.

 class Animal{
 Animal(){System.out.println("animal is created");}
 }
 class Dog extends Animal{
 Dog(){
 System.out.println("dog is created");
 }
 }
 class TestSuper4{
 public static void main(String args[]){
 Dog d=new Dog();
 }}
super example: real use

 class Person{
 int id;
 String name;
 Person(int id,String name){
 this.id=id;
 this.name=name;
 }
 }
 class Emp extends Person{
 float salary;
 Emp(int id,String name,float salary){
 super(id,name);//reusing parent constructor