0% found this document useful (0 votes)
29 views

Oops in Java - 5

Class represents a blueprint for objects. It defines properties and behaviors but does not allocate memory. An object is an instance of a class that allocates memory and can access properties and behaviors defined in its class. Methods define behaviors or actions of objects. A class can contain fields, methods, constructors, and nested classes/interfaces. Static members are accessed by the class name while non-static members are accessed by object references as they are allocated memory per object instance.

Uploaded by

aishwaryakale278
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Oops in Java - 5

Class represents a blueprint for objects. It defines properties and behaviors but does not allocate memory. An object is an instance of a class that allocates memory and can access properties and behaviors defined in its class. Methods define behaviors or actions of objects. A class can contain fields, methods, constructors, and nested classes/interfaces. Static members are accessed by the class name while non-static members are accessed by object references as they are allocated memory per object instance.

Uploaded by

aishwaryakale278
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

Oops in Java

Class, Object and Method

Class: - When we say class which means it represents generic term through which we can
indicate the group of object.

In other word, it is imaginary world or blueprint of objet, when we say human being, we
won’t make out anything until we say some individual name.

When we say animal, we won’t make out anything until we say some individual animal
name. without saying animal name, we can just imagine groups of animal object.

e.g.: Human being, Vehicle, Animal

Human being represents group of human objects (Ram, Shyam, Mohan)

Vehicle:

Vehicle represents groups of vehicle objects (Car, Bike, Truck)

Animal: -

Animal represents groups of animal objects (Cow, Bear, Ant)

Object: - Object Has properties and behaviours

For e.g. Ram has properties (height, weight, colour) and Behaviours like (Walk, Talk, Eat,
Sleep)

Cow Has Properties (color, weight, horn) and Behaviours like (Eat, Walk)

Car Has properties (Four wheel, Engine, Weight) and Behaviours like (Run, Sound)

Method: - Behaviours or Action of object is Method

e.g. Walk, Talk, Eat, Sleep, Run, Sound

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Structure of Class

Example of Class, Method and Object

// package is location where you have this class in your system


package classObject;

// class name Example1


// public is access to class
public class Example1 {

// instance variable OR global variable OR Class Variable


int i;
int j;

// method with public access


// public is access to method and void is return type
// int k is local variable to method
public void test(int k) {
System.out.println("I am method");
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
}

// main method is always public and static


// program execution start from main method
// main will always have argument of string array
public static void main(String[] args) {
// object creation
Example1 obj = new Example1();
// method call through object reference
obj.test(5);
}
}

Object Reference will be created into stack Area where as Object will be created in heap
Area

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Method have following parts

• Access specifier It is optional as it tells the compiler how to call public, private,
and others specifier.
• Return Type: sometimes a method may return a value or does not return a value (for
that we use void).
• Name of method: This is to assign name of method.
• Parameters: a comma-delimited list of input parameters, preceded by their data
types, enclosed by parentheses. If there are no parameters, you must use empty
parentheses.
• Body of method: The method body enclosed between braces contains a collection of
statements that define what the method does.

Point to remember

• First Line of class is always package Name


• Public is access of Class
• int i, int j is class variables
public void test(int k)

• Method first String "Public" is access to method


• "int k" is local variable to method
• void is return type of method
public static void main(String[] args)

• Main method is always static method


• Return type of main method is always void
• Main method return type is always Array of String
A class in Java can contain:

• fields
• methods
• constructors
• blocks
• nested class and interface
Example2:

package com.coreJava;

public class Test {


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// field or data member or instance variable
int id;
String name;

public static void main(String args[]) {

//creating an object of Student


Test s1 = new Test();
//accessing member through reference variable
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Static and Non-Static Member Of Class

Static Members of class are accessed by class Name, since static members are class
members, Non-Static members of class are accessed by object. Non-Static members are
object members.

Difference Between Static and non-Static Variable in Java

The variable of any class are classified into two types;

• Static or class variable

• Non-static or instance variable

Static variable in Java

Memory for static variable is created only one in the program at the time of loading of
class. These variables are preceded by static keyword. static variable can access with class
reference.

Non-static variable in Java

Memory for non-static variable is created at the time of create an object of class. These
variable should not be preceded by any static keyword Example: These variables can
access with object reference.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package staicAndNonStatic;

public class Example1 {

// create non static instance variable


public int i = 90;
// create static variable
public static int j = 80;

// create main method


public static void main(String[] args) {
// create object of class
Example1 obj = new Example1();
int k = obj.i;
// through object we can call non static
System.out.println(obj.i);
// when we call static member we get warning message but it is allowed
System.out.println(obj.j);
// through class reference we can call only static member
System.out.println(Example1.j);

// we can not call non-static members through class Name


// if we do so we will get compile time error.
System.out.println(Example1.i);
}
}

Non Static Static

These variable should not be preceded by any These variables are preceded by static
static keyword Example: keyword.

public class A public class A


{ {
int a; static int b;
} }

Memory is allocated for these variable whenever Memory is allocated for these variable at
an object is created the time of loading of the class.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Memory is allocated multiple time whenever a Memory is allocated for these variable
new object is created. only once in the program.

Non-static variable also known as instance Memory is allocated at the time of loading
variable while because memory is allocated of class so that these are also known as
whenever instance is created. class variable.

Static variable are common for every


object that means there memory location
can be sharable by every object reference
Non-static variable are specific to an object or same class.
Non-static variable can access with object Static variable can access with class
reference. reference.
Syntax Syntax
obj_ref.variable_name class_name.variable_name

Note: static variable not only can be access with class reference but also some time it can be
accessed with object reference.

Why static method can access only static data.

Static Data is similar to a static method. A value that is declared static has no associated
instance. It exists for every instance, and is only declared in a single place in memory. If it
ever gets changed, it will change for every instance of that class.

A Static Method can access Static Data because they both exist independently of specific
instances of a class.

package staicAndNonStatic;

public class Example2 {

// create non static method


public void test1(){
System.out.println("test1 is non-static method");
}

// create static method


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public static void test2(){
System.out.println("test2 is static method");
}

// create main method


public static void main(String[] args) {
// create object of class to call non-static members
Example2 obj = new Example2();
obj.test1();
// for static method we call through class name
Example2.test2();
}

Key Points to Remember

• static methods in Java are resolved at compile time. Since method overriding is part
of Runtime Polymorphism, so static methods can’t be overridden
• abstract methods can’t be static
• static methods cannot use this or super keywords
• The following combinations of the instance, class methods and variables are valid:
1. Instance methods can directly access both instance methods and instance
variables
2. Instance methods can also access static variables and static methods directly
3. static methods can access all static variables and other static methods
4. static methods cannot access instance variables and instance methods
directly; they need some object reference to do so

Q) why java main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm
create object first then call main() method that will lead the problem of extra memory
allocation.

package staicAndNonStatic;

public class Example3 {

// create non-static instance variable


public int i = 90;
// create static variable
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public static int j = 60;

// non static method will access both static and non static
public void test1(){
System.out.println(i);
System.out.println(j);
}
// static method will access only static
public static void test2(){
// we will get compile time error when we access non static from static
method.
// and i is non static
System.out.println(i);
System.out.println(j);
}
// main method is always static since it does not require object to call
public static void main(String[] args) {
// create object
Example3 obj = new Example3();
// we can call static method directly in main method. since main method is
static
test2();
// when we call non static directly without object we will get compile time
error.
test1();
}

package staicAndNonStatic;

public class Example4 {


// static variables
public static int counter = 0;
// non static instance variables
public int i = 0;

// creating constructor
Example4(){
// we are changing the value of instance and static variables
counter++;
i++;
System.out.println("value of i is: "+ i +" value of counter is "+ counter);
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public static void main(String[] args) {
// create three object
Example4 obj1 = new Example4();
Example4 obj2 = new Example4();
Example4 obj3 = new Example4();
}

// here value of i is always i because every object will get one copy of non static member.
// where as counter value will change, since static is not per object, it is get executed per
class
/**
value of i is: 1 value of counter is 1
value of i is: 1 value of counter is 2
value of i is: 1 value of counter is 3
*/

package staicAndNonStatic;
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public class Example5 {
// non static instance variable
public int rollNumber;
public int age;
// static variable
public static String collegeName = "BIT";

// constructor is used to create object.


// and initialize the instance variable
Example5(int rollNum, int ageData){
rollNumber = rollNum;
age = ageData;
}

// display method will display all student data


public void display(){
System.out.println("rollNumber: "+rollNumber +" age "+age+" collegeName
"+ collegeName);
}

public static void main(String[] args) {


// create object with two argument, since we have constructor with two
arguments
Example5 obj = new Example5(100,23);
// call display method on obj object.
obj.display();
Example5 obj1 = new Example5(101,24);
// call display method on obj1 object.
obj1.display();
Example5 obj2 = new Example5(102,25);
// call display method on obj2 object.
obj2.display();
}
}
// in this rollNumber and age is different for object but college is always same so I kept
college name as static
/**
rollNumber: 100 age 23 collegeName BIT
rollNumber: 101 age 24 collegeName BIT
rollNumber: 102 age 25 collegeName BIT
*/

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Naming convention in Java

Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color,
Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g.
Runnable, Remote, ActionListener etc.

method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.

variable name should start with lowercase letter e.g. firstName, orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY
etc.

Constructor in Java

• In Java constructor is similar to method. It is called when we create object of class.


• Constructor Name is same as class Name.
• Constructor cannot have return type.
• When we don’t create constructor in class, Java compiler will keep by default
constructor in class.

Types of Constructor:

Constructor

Default(No arg
Parameterized
constructor)
Syntax:

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package constructorInjava;

public class Test1 {

// create two instance variable


int a;
int b;

// create constructor with two argument


public Test1(int a, int b) {
this.a = a;
this.b = b;
}
// create default constructor
public Test1() {
}

• Default constructor will not have any argument.


• Parameterised constructor will have argument.

package constructorInjava;

public class Example2 {

// create two instance variable


int a;
int b;

// create constructor with two arguments.


public Example2(int a, int b) {
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// using this keyword to differentiate between instance and local
// variable
this.a = a;
this.b = b;
System.out.println("I am Test1(int a, int b)");
}

// create default constructor


public Example2() {
System.out.println("I am Test1()");
}

// create main method


public static void main(String[] args) {
// create object of default constructor
// this will call Example2() constructor
Example2 obj = new Example2();
// create object of parameterized constructor
// this will call Example2(int a, int b) constructor
Example2 obj1 = new Example2(2, 3);
}

Output:
I am Test1()
I am Test1(int a, int b)

Q: Is it possible to create object of default constructor when we have only parameterized


constructor in class.

Answer: No, when we keep parameterized constructor in class in that case Java compiler
will not keep default constructor in class.

Example:
package constructorInjava;
package constructorInjava;

public class Test1 {

// create two instance variable


int a;
int b;

// create constructor with two argument


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public Test1(int a, int b) {
// using this keyword to between instance and local variable
// through method instance variables will get initialized
this.a = a;
this.b = b;
System.out.println("I am Test1(int a, int b)");
}

// create main method


public static void main(String[] args) {

// when we create object of default constructor we will get compile time


error.
// because when we have only parameterized constructor in class in that case
we
// can't create object of default constructor
Test1 obj = new Test1();

// this object is perfectly fine


Test1 obj1 = new Test1(2, 3);
}

Test1 obj = new Test1();


This object is not allowed. It will give compile time error.

Use of Constructor

• The purpose of constructor is to initialize the object of a class


• Default constructor is used to provide the default values to the object like 0, null etc.
depending on the type.
• Parameterized constructor is used to provide different values to the distinct objects.

Q: Is constructor overloading is possible.

Answer: Yes

package constructorInjava;

public class Example3 {

// Constructor with one argument


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Example3() {

}
// Constructor with two argument
Example3(int i, int j) {

}
// Constructor with three argument
Example3(int i, int j, int k) {

// we call this as Constructor overloading and Constructor call happens


// based on argument supplied to object
}

Constructor call Example

package constructorInjava;

public class Example4 {

// Constructor with one argument


Example4() {
System.out.println("I am Example4()");
}
// Constructor with two argument
Example4(int i, int j) {
System.out.println("I am Example4(int i, int j)");
}
// Constructor with three argument
Example4(int i, int j, int k) {
System.out.println("I am Example4(int i, int j, int k)");
}

public static void main(String[] args) {


// Here Based on argument constructor will get called
// obj object will call Example4()
Example4 obj = new Example4();
// obj1 object will call Example4(int i, int j)
Example4 obj1 = new Example4(2, 3);
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// obj2 object will call Example4(int i, int j, int k)
Example4 obj2 = new Example4(3, 4, 5);
}
}

Output:

I am Example4()
I am Example4(int i, int j)
I am Example4(int i, int j, int k)

constructor is also used o initialize the instance member of a class

package constructorInjava;

public class Example6 {

// create two instance variable


int a;
int b;

// create constructor with two arguments.


public Example6(int a, int b) {
// using this keyword to differentiate between instance and local
// variable
this.a = a;
this.b = b;
}

// create default constructor


public Example6() {
System.out.println("I am Test1()");
}

// create main method


public static void main(String[] args) {
// create object of default constructor
// this will call Example2() constructor
Example6 obj = new Example6();
// create object of parameterized constructor
// this will call Example2(int a, int b) constructor
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Example6 obj1 = new Example6(2, 3);
// here a and b will get initialized by 2, 3
System.out.println(obj1.a);
System.out.println(obj1.b);
}

Output:

2
8

Return Type in Java

In Java, method return type is the value returned before a method completes its execution
and exits

Type of the return value must match the method's declared return type We can't return an
integer value from a method whose declaration type is void.

package returnTypeInJava;

public class ReturnTypeInJava {

// this method will not return anything


// so return type is void
public void test1() {
}
// this method will return integer data
public int test2() {
return 3;
}
// this method will return double data
public double test3() {
return 3.99;
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// this method will return boolean data
public boolean test4() {
return true;
}
// this method will return char data
public char test5() {
return 'a';
}
// this method will return String data
public String test6() {
return "Test";
}
// this method will return instance of object
public ReturnTypeInJava test7() {
return new ReturnTypeInJava();
}
// this method will return one dimensional array
public int[] test8() {
return new int[7];
}

public static void main(String[] args) {


ReturnTypeInJava obj = new ReturnTypeInJava();

int a[] = new int[5];


}
}

• In test1() method when we try to return integer data we will get compile time
error. since method declaration type is void
• In test2() method when we try to return String data we will get compile time error.
since method declaration type is Integer
• In test3() method when we try to return String data we will get compile time error.
since method declaration type is double
• In test4() method when we try to return void data we will get compile time error.
since method declaration type is Boolean
• In test7() method we are returning object since method declaration is class type.
• object declaration syntax
• Example1 obj = new Example1(); that's why we are returning new Example1() for
method test7()
• test8() method we are returning array object since method declaration is array type.
• object declaration syntax for array
• int[] a = new int[7]; that's why we are returning new int[7] for method test8()

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Access Modifier

Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −

• Visible to the package, the default. No modifiers are needed.


• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses (protected).

Private Access Modifier - Private


Methods, variables, and constructors that are declared private can only be accessed within
the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.

Public Access Modifier - Public


A class, method, constructor, interface, etc. declared public can be accessed from any other
class. Therefore, fields, methods, blocks declared inside a public class can be accessed from
any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package, then the public
class still needs to be imported. Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.

Protected Access Modifier - Protected


Variables, methods, and constructors, which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can
be declared protected, however methods and fields in an interface cannot be declared
protected.

Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc.

A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.

Access Level of each type

Access Within Outside Within Same Outside Package(Through


Type Class Class Package Inheritance)
Public Yes Yes Yes Yes
Private yes No No No
Protecte yes Yes Yes Yes
d
Default yes Yes Yes No

Same Class

Access Type Within Class


Public YES
Private YES
Protected YES
Default YES

package modifier;

public class Example1 {

// Instance variable
public int i = 10;
int j = 20;
protected int k = 30;
private int p = 40;

// method with public access


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public void test1(){
System.out.println("public method");
}
// method with private access
private void test2(){
System.out.println("private method");
}
// method with default access
void test3(){
System.out.println("default method");
}
// method with protected access
protected void test4(){
System.out.println("protected method");
}

public static void main(String[] args) {


// create Object of class
Example1 obj = new Example1();
// we can access all members within class
obj.test1();
obj.test2();
obj.test3();
obj.test4();
// we can access all instance variable within class
System.out.println(obj.i);
System.out.println(obj.j);
System.out.println(obj.k);
System.out.println(obj.p);
}

Different Class same package

Access Type Outside Class


same package
Public YES
Private YES

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Protected YES
Default NO

package modifier;

public class Example2 {

public static void main(String[] args) {


Example1 obj = new Example1();
// we can access all members from outside class except private
obj.test1();
obj.test3();
obj.test4();
// we can access all instance variables from outside class except private
System.out.println(obj.i);
System.out.println(obj.j);
System.out.println(obj.k);
}

Different Package class without inheritance

Access Type outside Class different


package without inheritance
Public YES
Private NO
Protected NO
Default NO

package testModifier;

import modifier.Example1;

// we are in different package


public class Example3 {

public static void main(String[] args) {


// from different package we can access only public without inheritance
Example1 obj = new Example1();
obj.test1();
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
System.out.println(obj.i);

Different Package class with inheritance

Access Type outside Class different


package without inheritance
Public YES
Private NO
Protected YES
Default NO

package testModifier;

import modifier.Example1;

//we are in different package


public class Example4 extends Example1{

public static void main(String[] args) {


// from different package we can access only public and protected with
inheritance
Example4 obj = new Example4();
obj.test1();
obj.test4();

System.out.println(obj.i);
System.out.println(obj.k);

}
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
This in Java

This in Java
This is java keyword. It(this) works as a reference to the current Object.

Use of This Keyword


• It can be used to refer current class instance variable.
• this () can be used to invoke current class constructor.
• It can be used to invoke current class method (implicitly)
• It can be passed as an argument in the method call.
• It can be passed as argument in the constructor call.
• It can also be used to return the current class instance.
• It is available only for non-static.

Problem without this keyword

package thisInjava;

public class Example1 {

int i;
int j;

// example without this


// here instance variable will not be initialized, since global and local variable has
same name
Example1(int i, int j){
i = i;
j = j;
}

public static void main(String[] args) {


// create object of parameterized constructor
Example1 obj = new Example1(5,6);
System.out.println(obj.i);
System.out.println(obj.j);
}

}
/**
output
0
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
0
*/

Same program with this keyword

package thisInjava;

public class Example2 {

int i;
int j;
int k;

// Here instance variable will be initialized by local variable


// when you have local and global variable has same name, use this keyword to
differentiate
Example2(int i, int j){
this.i = i;
this.j = j;
}

// here we don't need this keyword. since instance and local variable is different
Example2(int i){
k = i;
}

public static void main(String[] args) {


// create object of constructor which has two argument
Example2 obj = new Example2(5,6);
System.out.println(obj.i);
System.out.println(obj.j);
// create object of constructor which has one argument
Example2 obj1 = new Example2(5);
System.out.println(obj1.k);
}
}

Output

5
6
5

this () can be used to invoke current class constructor.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package thisInjava;

public class Example3 {

Example3() {
System.out.println("default constructor");
}

Example3(int i) {
// this() will call Example3() constructor
this();
System.out.println("value of i is: "+i);
}

Example3(int i, int k) {
// this(i) will call Example3(int i) constructor
this(i);
System.out.println("value of i is: "+i+" and value of k is: "+k);
}

public static void main(String[] args) {


Example3 obj = new Example3(5,6);

}
}
/**
Output
default constructor
value of i is: 5
value of i is: 5 and value of k is: 6
*/

It can be used to invoke current class method (implicitly)

package thisInjava;

public class Example4 {

public void test1(){


System.out.println("test1");
}

public void test2(){


System.out.println("test2");

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// here we call method test1() through this keyword. since this refer current
class object
this.test1();
}

public static void main(String[] args) {


Example4 obj = new Example4();
obj.test2();
}

Output
test2
test1

It can be passed as an argument in the method call.

package thisInjava;

public class Example5 {

// we have method with class type argument


public void test1(Example5 obj) {
System.out.println("test1");
System.out.println(obj);
}

public void test2() {


// we can call test1() method with this as an argument since this refer
// current class object.
test1(this);

// other way to call method which has class type as an argument


Example5 obj = new Example5();
// obj is same as this.
test1(obj);

public static void main(String[] args) {


Example5 obj = new Example5();
obj.test2();
}
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
/**
output

test1
thisInjava.Example5@7852e922
test1
thisInjava.Example5@4e25154f
*/

It can be passed as argument in the constructor call.

package thisInjava;

public class Example6 {

int i;
// Create constructor with argument of different class type
Example6(Example7 obj){
// Example7 object has i data. so we are initializing instance variable i with
Example7 object data
i = obj.i;
}

void display(){
System.out.println("value of i is:"+ i);
}
}

package thisInjava;

public class Example7 {

int i = 90;

Example7() {
// Create object of Example6 and supply "this" as an argument.
// "this" is of type Example7, so Example6 constructor argument should be of
Example7 class type
Example6 obj = new Example6(this);
obj.display();
}

public static void main(String[] args) {


Example7 obj = new Example7();
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
}

Output:
value of i is:90

It can also be used to return the current class instance.

package thisInjava;

public class Example8 {

int i = 90;

public Example8 test1(){


// either return "this" or new Example8() both are same
return this;
}

public Example8 test2(){


return new Example8();
}

public static void main(String[] args) {


Example8 obj = new Example8();
}

This keyword is available only for non-static.

package thisInjava;

public class Example9 {

int i = 90;

public void test1() {


// in non-static we can use.
this.test3();
}

public static void test2() {


// in static method we cannot use "this". when we use we will get compile
time error.
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
//this.test2();
}

public void test3() {

public static void main(String[] args) {


Example9 obj = new Example9();
}

Method Overloading In Java

Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor
overloading in Java, that allows a class to have more than one constructor having different
argument lists.

Method Overloading will allow us to create more than one methods with same name by
changing the method arguments.
Method Overloading is called as compile time polymorphisms.

Arguments list can be different in following ways

1) Numbers of parameters to method

void method(int dataOne, int dataTwo){}

void method(float dataOne, float dataTwo, int dataThree){}

2) Sequence Type of parameters

void method(int dataOne, float dataTwo){}

void method(float dataOne, int dataTwo){}

What's the need of method overloading

1. Overloading is very useful in Java. In overloading we can overload methods as long


as the type or number of parameters (arguments) differ for each of the method.
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Suppose you need to perform a complex mathematical operation, but sometimes
need to do it with two numbers and sometimes three, etc.
2. In overloading a class can have multiple methods with the same name that can be
differentiated by the number and type of arguments passed into the method

Method have following parts

• Access specifier It is optional as it tells the compiler how to call public, private,
and others specifier.
• Return Type: sometimes a method may return a value or does not return a value (for
that we use void).
• Name of method: This is to assign name of method.
• Parameters: a comma-delimited list of input parameters, preceded by their data
types, enclosed by parentheses. If there are no parameters, you must use empty
parentheses.
• Body of method: The method body enclosed between braces contains a collection of
statements that define what the method does.

Advantages of method overloading in java

1. Overloading in Java is the ability to create multiple methods of the same name, but
with different parameters.
2. The main advantage of this is cleanliness of code.
3. Method overloading increases the readability of the program.
4. Overloaded methods give programmers the flexibility to call a similar method for
different types of data.
5. Overloading is also used on constructors to create new objects given different
amounts of data.
6. You must define a return type for each overloaded method. Methods can have
different return types

1) Numbers of parameters to method example

package methodOverloading;

public class Example1 {

// method with one argument


public void calculateArea(int lenght) {
System.out.println("calculateArea(int lenght)");
}

// method with two arguments


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public void calculateArea(int lenght, int height) {
System.out.println("calculateArea(int lenght, int height)");
}

// method with three arguments


public void calculateArea(int lenght, int height, int Width) {
System.out.println("calculateArea(int lenght, int height, int Width)");
}

public static void main(String[] args) {


// create object of class
Example1 obj = new Example1();
// here calculateArea method will get called which has two arguments
obj.calculateArea(20, 30);
// here calculateArea method will get called which has one argument
obj.calculateArea(20);
}
}
/**
Output
calculateArea(int lenght, int height)
calculateArea(int lenght)
*/

Overloaded Method call from different class

package methodOverloading;

public class Example2 {

public static void main(String[] args) {


// Create object Example1 class
Example1 obj = new Example1();
// here calculateArea method will get called which has one argument
obj.calculateArea(20);
}

2) Data Type sequence

package methodOverloading;

public class Example3 {


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// method with two arguments
public void add(int i, int j) {
System.out.println("add(int i, int j) ");
}
// method with two arguments but data type is different
public void add(double d1, double d2) {
System.out.println("add(double d1, double d2)");
}
// method with two arguments but data type is different
public void add(int d1, long d2) {
System.out.println("add(int d1, long d2)");
}
// method with two arguments but data type sequence is different
public void add(long d1, int d2) {
System.out.println("add(long d1, int d2)");
}

public static void main(String[] args) {


// create object of class
Example3 obj = new Example3();
// here add(double d1, double d2) method will get called
obj.add(30.98, 20.99);
//here add(int i, int j) method will get called
obj.add(30, 20);
}
}

/**
add(double d1, double d2)
add(int i, int j)
*/

Is it possible to have different return type for overloaded method


Answer: Yes

package methodOverloading;

public class Example4 {

// method with void return type


public void test() {

}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// method with int return type
public int test(int i) {
return i;
}
// method with boolen return type
public boolean test(String flag) {
if (flag.contains("test")) {
return true;
} else {
return false;
}
}

}
Is it possible to overload method just by changing return type
Answer: No

package methodOverloading;

public class Example5 {

// overloaded method with same argument but different return type.


// we will get compile time error.
public void test(int i) {

}
// overloaded method with same argument but different return type.
// we will get compile time error.
public int test(int i) {
return i;
}
}

Is it possible to overload main method


Answer: yes

package methodOverloading;

public class Example6 {

// main method
public static void main(String[] args) {
System.out.println("main(String[] args)");

Example6.main(5);
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
}

// overloaded main method


public static void main(String args) {
System.out.println("main(String args)");
}

// overloaded main method


public static void main(int args) {
System.out.println("main(int args)");
}
}
/**
Output
main(String[] args)
main(int args)
*/

Method Overloading and Type Promotion

byte can be promoted to short, int, long, float or double. The short datatype can be
promoted to int,long,float or double. The char datatype can be promoted to int,long,float or
double and so on

package methodOverloading;

public class Example7 {

// byte<short<int<long<float<double

/**
* This method will accept below data type combinations
* (byte,byte)
* (short,short)
* (int,int)
* (long,long)
* @param l1
* @param l2
*/
public void test1(long l1, long l2) {
System.out.println("test1(long l1, long l2)");
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
/**
* This method will accept below data type combinations, if test1(long l1, long l2)
method is not available
* (byte,byte)
* (short,short)
* (int,int)
* (long,long)
* (float,float)
*(double,double)
* @param l1
* @param l2
* since test1(long l1, long l2) is available so it will take only
* (float, byte)
* (float, int)
* (double, double)
* (long,float)
*/
public void test1(double l1, double l2) {
System.out.println("test1(double l1, double l2)");
}

/**
* This method will accept
* (float l1, float l2)
* @param l1
* @param l2
*/
public void test1(float l1, float l2) {
System.out.println("test1(float l1, float l2)");
}

public static void main(String[] args) {

Example7 obj = new Example7();


// this method data type will get promoted to test1(long l1, long l2) method
obj.test1(20, 10);
// this method data type will get promoted to test1(double l1, double l2)
method
obj.test1(20.90, 10.00);
// this method data type will get promoted to test1(float l1, float l2) method
obj.test1(20.90f, 10.0f);
}
}
/**
Output
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
test1(long l1, long l2)
test1(double l1, double l2)
test1(float l1, float l2)
*/

Example of Method Overloading with Type Promotion in case of ambiguity

package methodOverloading;

public class Example8 {

public void sum(int i, double d) {


System.out.println("sum(int i, double d)");
}

public void sum(double i, int d) {


System.out.println("sum(double i, int d)");
}

public static void main(String[] args) {


Example8 obj = new Example8();
// here compiler will get confused which overloaded method need to be
called
// since sum(int i, double d) will accept (20,10) and
// sum(double i, int d) will also accept (20,10)
// so we will see compile time error
obj.sum(20, 10);
}
}

On Run Time Method call happens based on the parameters supplied to method

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package methodOverloading;

public class Example2 {

public void test1(int i) {


System.out.println("Method with one argument");
}

public void test1(int i, int j) {


System.out.println("Method with two arguments");
}

public void test1(int i, int j, int k) {


System.out.println("Method with three arguments");
}

public static void main(String[] args) {


Example2 obj = new Example2();
obj.test1(4);
obj.test1(2, 3);
obj.test1(2, 3, 4);
}
}

// Output
// Method with one argument
// Method with two arguments
// Method with three arguments

Inheritance in Java

Points to Note:
• Through inheritance child class will acquire all non-static members of class.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
• Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

When we create object of child class, child class object will get all members of parent class
and child class.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Single Level Inheritance

package inherinatnceInJava;

public class ParentClass {

// Create non static method


public void test1() {
System.out.println("I am from Parent class test1()");

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
}
// Create non static method
public void test2() {
System.out.println("I am from Parent class test2()");
}
}

package inherinatnceInJava;

/**
* To use inheritance we have to use "extends" keyword
*/
public class ChildClass extends ParentClass{

public static void main(String[] args) {

// create object of child class.


// and child class will get all non-static methods of parent class
ChildClass obj = new ChildClass();
// here test1() and test2() method is coming from parent class
obj.test1();
obj.test2();
}
}

Output:
I am from Parent class test1()
I am from Parent class test2()

package inherinatnceInJava;

public class ParentClass1 {

// Create non static method


public void test1() {
System.out.println("I am from Parent1 class test1()");
}

// Create non static method


public void test2() {
System.out.println("I am from Parent1 class test2()");
}
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package inherinatnceInJava;

/**
* To use inheritance we have to use "extends" keyword
*/
public class ChildClass1 extends ParentClass1{

// child class method


public void test3() {
System.out.println("I am from child1 class Test3()");
}

public static void main(String[] args) {

// create object of child class.


// and child class will get all non-static methods of parent class
ChildClass1 obj = new ChildClass1();
// here test1() and test2() method is coming from parent class.
// test3() method we have in child class
obj.test3();
obj.test1();
obj.test2();
}
}

Output:
I am from child1 class Test3()
I am from Parent1 class test1()
I am from Parent1 class test2()

Private and Final Members in Inheritance

• During inheritance, we must declare methods with final keyword for which we
required to follow the same implementation throughout all the derived classes.

• The private member are not inherited because the scope of a private member
is only limited to the class in which it is defined.

package inherinatnceInJava;

public class ParentClass2 {

// default member
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
int i =90;
// public member
public int k =80;
// protected member
protected int p = 70;
// private member
private int l = 60;
// final member
final int r = 50;

// public method
public void test1() {
System.out.println("I am from Parent1 class test1()");
}

// protected method
protected void test2() {
System.out.println("I am from Parent1 class test2()");
}

// default method
void test3() {
System.out.println("I am from Parent1 class test3()");
}

// private method
private void test4() {
System.out.println("I am from Parent1 class test4()");
}

// final public method


final public void test5() {
System.out.println("I am from Parent1 class final method test5()");
}

// static public method


static public void test6() {
System.out.println("I am from Parent1 class final method test6()");
}
}

package inherinatnceInJava;

/**
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
* To use inheritance we have to use "extends" keyword
*/
public class ChildClass2 extends ParentClass2{

public static void main(String[] args) {

// create object of child class.


// and child class will get all non-static methods of parent class
ChildClass2 obj = new ChildClass2();
// here all methods are coming from parent class
obj.test1();
obj.test2();
obj.test3();
obj.test5();
// test6() is static method so we should not call through object
obj.test6();
// we can not call test4() method since it is private in parent class
// and we can't inherit private members. if we do so we will compile time
error
//obj.test4();

/**
* in case of instance variable also, except private we can inherit all
*/
System.out.println(obj.i);
System.out.println(obj.k);
System.out.println(obj.p);
System.out.println(obj.r);
}
}

Output:
I am from Parent1 class test1()
I am from Parent1 class test2()
I am from Parent1 class test3()
I am from Parent1 class final method test5()
I am from Parent1 class final method test6()
90
80
70
50

Q: Can we Inherit Constructor of class


Answer: No

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package inherinatnceInJava;

public class ParentClass3 {

// default constructor
ParentClass3() {
System.out.println("ParentClass3()");
}

// parameterized constructor
ParentClass3(int i) {
System.out.println("ParentClass3(int i) ");

}
}

package inherinatnceInJava;

public class ChildClass3 extends ParentClass3{

public static void main(String[] args) {


// we can't inherit constructor of parent class.
// if we do so we will get compile time error
ChildClass3 obj = new ChildClass3(7);
}
}

Is It possible to Create Reference of Parent Class and Object of Child Class

package inherinatnceInJava;

public class ParentClass4 {

// test1() method with default access type


void test1(){
System.out.println(" I am from ParentClass4");
}
}

package inherinatnceInJava;

public class ChildClass5 extends ParentClass4{

// test2() method with default access type


void test2(){
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
System.out.println("I am from ChildClass5");
}

public static void main(String[] args) {


// create reference of parent class and object of child class
ParentClass4 obj = new ChildClass5();
// in that case we call only test1() method. since at compile time method call
happens from reference class.
obj.test1();

// create reference and object of child class


ChildClass5 obj1 = new ChildClass5();
// in that case we can call both the method since child class has both the
method.
obj1.test1();
obj1.test2();
}
}

Output:
I am from ParentClass4
I am from ParentClass4
I am from ChildClass5

Multilevel inheritance

package inherinatnceInJava;

public class A {

// instance variable
int i = 90;

// public method
public void test1(){
System.out.println("A");
}
}

package inherinatnceInJava;

/**
* Here B is child class and A is parent class
*/
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public class B extends A {

// test2() is public method


public void test2() {
System.out.println("B");
}
}

package inherinatnceInJava;

/**
* Here B is child class and A is parent class
*/
public class C extends B {

// test3() public method


public void test3() {
System.out.println("C");
}

public static void main(String[] args) {


// create object of C class
C obj = new C();
// here C class will all members of A and B class
// since C extends B extends A
obj.test1();
obj.test2();
obj.test3();

// i is getting called from A class


System.out.println(obj.i);
}
}

Output:
A
B
C
90

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
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 same method and you call it from child class object, there will be
ambiguity to call 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 now.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package inheritance;

public class A {
void test() {
System.out.println("Welcome");
}
}

package inheritance;

public class B {
void test() {
System.out.println("Welcome");
}
}

package inheritance;

public class C extends A,B


{ //suppose if extends A, B

public static void main(String args[]) {


C obj = new C();
obj.test();// Now which test() method would be invoked?
}
}

Output:
Compile time error.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Super keyword in java

The super keyword refers to the objects of immediate parent class.

When Need of super keyword

Whenever the derived class is inherits the base class features, there is a possibility that
base class features are similar to derived class features and JVM gets an ambiguity. In order
to differentiate between base class features and derived class features must be preceded
by super keyword.

Usage of java super Keyword

1) To access the data members of parent class when both parent and child class have
member with same name
2) To explicitly call the no-arg and parameterized constructor of parent class.
3) To access the method of parent class when child class has overridden that method.

1) How to use super keyword to access the variables of parent class

When you have a variable in child class which is already present in the parent class then in
order to access the variable of parent class, you need to use the super keyword.

package superInJava;

public class Example1 {


// create one instance variable
public String color = "white";
}

package superInJava;

/**
* To use inheritance child class has to extends parent class
*
*/
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public class Example2 extends Example1{

// override color of parent class


public String color = "black";

// this method will display color


void display(){
// this print will call color from child class
System.out.println("color is: "+color);
// this "super.color" will get called from parent class
System.out.println("color is: "+super.color);
}

public static void main(String[] args) {


// create object
Example2 obj = new Example2();
obj.display();
}

Output:
color is: black
color is: white

2) Use of super keyword to invoke constructor of parent class

When we create the object of sub class, the new keyword invokes the constructor of child
class, which implicitly invokes the constructor of parent class. So the order to execution
when we create the object of child class is: parent class constructor is executed first and
then the child class constructor is executed. It happens because compiler itself adds
super()(this invokes the no-arg constructor of parent class) as the first statement in the
constructor of child class.

package superInJava;

public class Example3 {

// create two instance variable


int salary;
int age;

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// create default constructor
Example3() {
System.out.println("I am parent constructor");
}

// create parameterized constructor


Example3(int salary, int age) {
this.salary = salary;
this.age = age;
}

// this will get salary which is initialized by parameterized constructor


public int getSalary(){
return salary;
}

// this will get age which is initialized by parameterized constructor


public int getAge(){
return age;
}

package superInJava;

public class Example4 extends Example3 {

// create instance variable


String name;

// create parameterized constructor


Example4(String name, int salary, int age){
// first line of constructor
// this super will call parent class "Example3(int salary, int age)"
super(salary, age);
this.name = name;
}

Example4(){
// when we don't write super(), then compile will keep by default and this
will call default constructor of parent class
//super();
System.out.println("I am child constructor");
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
void display(){
System.out.println("name is: "+name+" salary is: "+salary+" age is: "+age);
}
public static void main(String[] args) {
// create object of parameterized constructor
Example4 obj = new Example4("Bhanu",2000,30);
// call display method
obj.display();
// getAge() and getSalary() is getting called from parent class
System.out.println(obj.getAge());
System.out.println(obj.getSalary());
// create object of default constructor
Example4 obj1 = new Example4();

}
}

Output:
name is: Bhanu salary is: 2000 age is: 30
30
2000
I am parent constructor
I am child constructor

Super is used to invoke parent class method.

package superInJava;

public class Example5 {

// create run method


public void run(){
System.out.println("I am run method from parent class");
}

public void test(){


System.out.println("I am test method from parent class");
}

package superInJava;
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public class Example6 extends Example5{

// override run method from parent class


public void run(){
System.out.println("I am run method from child class");
}

// display method will call run method


public void display(){
// this run method will get called from child class
run();
// this run method will get called from parent class
super.run();
// this test method will get called from parent class, since we have not
overridden in child class
test();
}

public static void main(String[] args) {


Example6 obj = new Example6();
obj.display();
}
}

Output:
I am run method from child class
I am run method from parent class
I am test method from parent class

Real Time Example

package inherinatnceInJava;

public class Animal {

// private instance member


private boolean vegetarian;
// private instance member
private String eats;
// private instance member
private int noOfLegs;

// default constructor
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public Animal(){}

// parameterized constructor
public Animal(boolean veg, String food, int legs){
// we are initializing instance variable through this constructor
this.vegetarian = veg;
this.eats = food;
this.noOfLegs = legs;
}

// public getter method to get data from different class


public boolean isVegetarian() {
return vegetarian;
}

// public setter method to set data from different class


public void setVegetarian(boolean vegetarian) {
this.vegetarian = vegetarian;
}

// public getter method to get data from different class


public String getEats() {
return eats;
}

// public setter method to set data from different class


public void setEats(String eats) {
this.eats = eats;
}

// public getter method to get data from different class


public int getNoOfLegs() {
return noOfLegs;
}

// public setter method to set data from different class


public void setNoOfLegs(int noOfLegs) {
this.noOfLegs = noOfLegs;
}

package inherinatnceInJava;

public class Cow extends Animal{


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// private instance member
private String color;

// parameterized constructor
public Cow(boolean veg, String food, int legs) {
// super will call Animal constructor which has three argument
super(veg, food, legs);
// here we are initializing color with white
this.color="White";
}

// parameterized constructor
public Cow(boolean veg, String food, int legs,String color){
super(veg, food, legs);
// here we are initializing color with constructor argument
this.color=color;
}

// public getter method to get data from different class


public String getColor() {
return color;
}

// public setter method to set data from different class


public void setColor(String color) {
this.color = color;
}

package inherinatnceInJava;

public class AnimalInheritanceTest {

public static void main(String[] args) {

// create object of Cat class.


// this object will initialize all instance variable
Cow cow = new Cow(false, "milk", 5, "white");

// call getter method from Cat class.


// this will display the data which we set through object
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
System.out.println("Cow is Vegetarian?" + cow.isVegetarian());
System.out.println("Cow eats " + cow.getEats());
System.out.println("Cow has " + cow.getNoOfLegs() + " legs.");
System.out.println("Cow color is " + cow.getColor());

System.out.println("------------");
// we can set the instance variables.
cow.setColor("black");
cow.setEats("chicken");
cow.setNoOfLegs(3);
cow.setVegetarian(true);
// call getter method from Cat class
System.out.println("Cow is Vegetarian?" + cow.isVegetarian());
System.out.println("Cow eats " + cow.getEats());
System.out.println("Cow has " + cow.getNoOfLegs() + " legs.");
System.out.println("Cow color is " + cow.getColor());

Output:

Cow is Vegetarian?false
Cow eats milk
Cow has 5 legs.
Cow color is white
------------
Cow is Vegetarian?true
Cow eats chicken
Cow has 3 legs.
Cow color is black

Parameterized super() call to invoke parameterized constructor of parent class

when we have a constructor in parent class that takes arguments then we can use
parameterized super, like super(7); to invoke parameterized constructor of parent class
from the constructor of child class.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package superKeywordInJava;

public class G {

G(int i) {
System.out.println("G(int i)");
}

G() {
System.out.println("G()");
}

package superKeywordInJava;

public class H extends G{


H() {
super(7);
System.out.println("F is created");
}

public static void main(String[] args) {


H obj = new H();
}

Output:
G(int i)
F is created

When we don’t write super keyword in child class constructor, java compiler will provide
super () calling statement as first line of child constructor.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package superKeywordInJava;

public class I {
I() {
System.out.println("I");
}

package superKeywordInJava;

public class J extends I {

J() {
// Here Java compiler will keep super () by
default when we do not write.

System.out.println("J");
}

System.out.println("J");
}

public static void main(String[] args) {


J obj = new J();
}

Output:
I
J

Ream Time use of Super.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package superKeywordInJava;

public class Person {


int id;
String name;

Person(int id,String name){


this.id=id;
this.name=name;
}
}

package superKeywordInJava;

public class Emp extends Person {


float salary;

Emp(int id, String name, float salary) {


super(id, name);// calling parent constructor
this.salary = salary;
}

void display() {
System.out.println("id: "+id + " name: " +
name + " salary: " + salary);
}

public static void main(String[] args) {


Emp obj = new Emp(4,"Bhanu",900f);

obj.display();
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Output:

id: 4 name: Bhanu salary: 900.0

Points to Remembers:

Important Points for Inheritance in Java

1. Most important benefit of inheritance is code reuse because subclasses inherits the
variables and methods of superclass.
2. Private members of superclass are not directly accessible to subclass. As in this exam
ple, Animal variable noOfLegs is not accessible to Cat class but it can be indirectly acc
essible via getter and setter methods.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
3. Superclass members with default access is accessible to subclass ONLY if they are in s
ame package.
4. Superclass constructors are not inherited by subclass.
5. If superclass doesn’t have default constructor, then subclass also needs to have an e
xplicit constructor defined. Else it will throw compile time exception. In the subclass
constructor, call to superclass constructor is mandatory in this case and it should be t
he first statement in the subclass constructor.
6. Java doesn’t support multiple inheritance, a subclass can extends only one class. So h
ere Animal is implicitly extending Object class and Cat is extending Animal class but d
ue to java inheritance transitive nature, Cat class also extends Object class.
7. We can create an instance of subclass and then assign it to superclass variable, this is
called upcasting. Below is a simple example of upcasting:

Cat c = new Cat(); //subclass instance

Animal a = c; //upcasting, it's fine since Cat is also an Animal

8. When an instance of Superclass is assigned to a Subclass variable, then it’s called do


wncasting. We need to explicitly cast this to Subclass. For example;

Cat c = new Cat();


Animal a = c;
Cat c1 = (Cat) a; //explicit casting, works fine because "c" is actually of type Cat

Note that Compiler won’t complain even if we are doing it wrong, because of explicit casting
. Below are some of the cases where it will throw ClassCastException at runtime.

Dog d = new Dog();


Animal a = d;
Cat c1 = (Cat) a; //ClassCastException at runtime
Animal a1 = new Animal();
Cat c2 = (Cat) a1; //ClassCastException because a1 is actually of type Animal at
runtime

9. We can override the method of Superclass in the Subclass. However we should alwa
ys annotate overridden method with @Override annotation so that Compiler knows
that we are overriding a method and if something changes in the superclass method,
we get to know at compile time rather than getting unwanted results at the runtime.
10. We can call the superclass methods and access superclass variables using super keyw
ord. It comes handy when we have a same name variable/method in the subclass bu
t we want to access the superclass variable/method. This is also used when Construc
tors are defined in the superclass and subclass and we have to explicitly call the supe
rclass constructor.
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
11. We can use instanceof instruction to check the inheritance between objects, let’s se
e this with below example.

Cat c = new Cat();


Dog d = new Dog();
Animal a = c;

boolean flag = c instanceof Cat; //normal case, returns true

flag = c instanceof Animal; // returns true since c is-an Animal too

flag = a instanceof Cat; //returns true because a is of type Cat at runtime

flag = a instanceof Dog; //returns false for obvious reasons.

12. We can’t extend Final classes in java.

If you are not going to use Superclass in the code i.e your Superclass is just a base to keep re
usable code then you can keep them as Abstract class to avoid unnecessary instantiation by
client classes. It will also restrict the instance creation of base class.

Method overriding In Java

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Points to Note: -
• Method Overriding is the feature of java which allow us to create same method in
parent and child class with same name and with same arguments.
• Method Overriding is the ability of java which will make sure method call will happen
from a class for which we have created the object. Not from referenced class.
• At compile time method call happens from reference class.
• At Run time method call happens from object class.
• Method Overriding is possible only by inheritance.
• Method Overriding, we also call it as run time polymorphism.
• We cannot override private members.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
• We cannot override final members.

• We cannot override static members.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
• We cannot override constructor as parent and child class can never have constructor
with same name(Constructor name must always be same as Class name).
• The overriding method must have same return type (or subtype)

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Advantage of method overriding

The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class code.

This is helpful when a class has several child classes, so if a child class needs to use the
parent class method, it can use it and the other classes that want to have different
implementation can use overriding feature to make changes without touching the parent
class code.

Method Overriding and Dynamic Method Dispatch

Method Overriding is an example of runtime polymorphism. When a parent class reference


points to the child class object then the call to the overridden method is determined at
runtime, because during method call which method(parent class or child class) is to be
executed is determined by the type of object. This process in which call to the overridden
method is resolved at runtime is known as dynamic method dispatch.

Rules of method overriding in Java

1. Argument list: The argument list of overriding method (method of child class) must
match the Overridden method(the method of parent class). The data types of the
arguments and their sequence should exactly match.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
2. Access Modifier of the overriding method (method of subclass) cannot be more
restrictive than the overridden method of parent class. For e.g. if the Access Modifier
of parent class method is public then the overriding method (child class method )
cannot have private, protected and default Access modifier,because all of these three
access modifiers are more restrictive than public.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
At compile time method call happens from reference class. At Run Time method call
happens from object Class

package methodOverridding;

public class Example1 {

// parent class method


public void test(){
System.out.println("I am from Example1 parent class");
}
}

package methodOverridding;

/**
* To override parent class method need to extends parent class
*/
public class Example2 extends Example1{

// Overridden method
public void test(){

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
System.out.println("I am from Example2 child class");
}

public static void main(String[] args) {


Example1 obj = new Example2();
// method call will happen from child class on run time
obj.test();
}
}

Output:
I am from Example2 child class

Real use of Method overriding

package methodOverridding;

public class Example1 {

// parent class method


public void test(){
System.out.println("I am from Example1 parent class");
}
}

package methodOverridding;

/**
* To override parent class method need to extends parent class
*/
public class Example2 extends Example1{

// Overridden method
public void test(){
System.out.println("I am from Example2 child class");
}

public static void main(String[] args) {


Example1 obj = new Example2();
// method call will happen from child class on run time
obj.test();
}
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package methodOverridding;

public class Example3 extends Example1{

// Overridden method
public void test(){
System.out.println("I am from Example3 child class");
}

package methodOverridding;

public class Example4 extends Example1{

// here I would like to use same


// test() method from parent class
}

package methodOverridding;

public class TestOverridding {

public static void main(String[] args) {

// Create reference for parent class


// object of child class
Example1 obj = new Example2();
// in Example2 we have overridden test() method
// so method call will happen from child class
obj.test();
// Create reference for parent class
// object of child class
Example1 obj1 = new Example3();
// in Example2 we have overridden test() method
// so method call will happen from child class
obj1.test();

Example1 obj2 = new Example4();


// test() method call will happen from parent class
// since we don't have overridden test() method
obj2.test();
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
}

Output:
I am from Example2 child class
I am from Example3 child class
I am from Example1 parent class

Another real use of overriding.

package methodOverridding;

public class Mobile {


void sendMessage(){
System.out.println("it will send message");
}
}

package methodOverridding;

public class Nokia extends Mobile{

// Nokia wants to use sendMessage() from Mobile class


// so Nokia is not overriding
}

package methodOverridding;

public class Samsung extends Mobile{

// Overridden method
void sendMessage(){
System.out.println("Samsung message");
}
}

package methodOverridding;

public class TestOverridding {

public static void main(String[] args) {

// Create reference for parent class


// object of child class
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Mobile mob = new Samsung();
// for Samsung sendMessage() overridden method will get called
mob.sendMessage();
Mobile nok = new Nokia();
// for Nokia sendMessage() will get called from parent class
nok.sendMessage();
}

Output
Samsung message
it will send message

We cannot override final method. When we try to do so we will get compile time error.
Static method will not participate in overriding.
Private method will not participate in overriding.

package methodOverridding;

public class Example5 {

private void test1(){


System.out.println("private from parent class");
}

static public void test2(){


System.out.println("static from parent class");
}

public void test4(){


System.out.println("non- static from parent class");
}

final public void test3(){


System.out.println("final from parent class");
}

package methodOverridding;

public class Example6 extends Example5{

// Through it looks like we are overriding.


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// but when we make reference of parent class.
// we can not call this method
private void test1(){
System.out.println("private from child class");
}
// Through it looks like we are overriding.
// but method call will happen from reference class.
// not object class. so this is not called as method overriding.
static public void test2(){
System.out.println("static from child class");
}
public void test4(){
System.out.println("non- static from child class");
}
// when we override final method we will get compile time error.
final public void test3(){
System.out.println("final from child class");
}

public static void main(String[] args) {


Example5 obj = new Example6();
// here test1() method is not available
// test2() will get called from parent class only.
obj.test2();
obj.test4();

Example6 obj1 = new Example6();


obj1.test1();
obj1.test2();
}
}

The argument list of overriding method (method of child class) must match the
Overridden method(the method of parent class). The data types of the arguments and
their sequence should exactly match.

package methodOverridding;

public class A {
public void test(int a, double b){
System.out.println("from A");
}
}

package methodOverridding;
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public class B extends A{

public void test(int a, int d){


System.out.println("from B");
}

public static void main(String[] args) {


A obj = new B();
// here method call will happen from parent class
// though we have overridden method
// because argument type in child class is not same as parent class
obj.test(3, 5.99999999);
}
}

Output:
from A

To correct Above code so that it will participate in method overriding.

package methodOverridding;

public class A {
public void test(int a, double b){
System.out.println("from A");
}
}

package methodOverridding;

public class B extends A{

public void test(int a, double d){


System.out.println("from B");
}

public static void main(String[] args) {


A obj = new B();
// here method call will happen from parent class
// though we have overridden method
// because argument type in child class is not same as parent class
obj.test(3, 5.99999999);
}
}
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Output:
from B

Overridden method return type should be same in child class.

package methodOverridding;

public class C {

// method with integer type return type


int test1(){
System.out.println("test1() from C");
return 5;
}
}

package methodOverridding;

public class D extends C{

// compile time error. since return type is not same as


// parent class
void test1(){
System.out.println("test1() from D");
}
}

Correct Above code

package methodOverridding;

public class C {
// method with integer type return type
int test1(){
System.out.println("test1() from C");
return 5;
}
}

package methodOverridding;

public class D extends C{

// compile time error. since return type is not same as


Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// parent class
int test1(){
System.out.println("test1() from D");
return 2;
}

public static void main(String[] args) {


C obj = new D();
obj.test1();
}
}

Output:
test1() from D

Interface in Java

• Interface has only unimplemented methods.


• Interface members are by default (Public static final).

• We call interface as 100 % abstract class.


• Multiple inheritance is possible in case of interface.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
• We cannot create object of interface, since all the members are unimpeded.
• We cannot create constructor of interface. Since object creation for interface is not
possible.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
• We cannot create object of interface. Since members are unimplemented.

Class Implements Interface

Interface extends Interface

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Structure of interface

public interface Example1 {


public final static int i=90;
int j =80;

public void test1();


public void test2();
public void test3();
public void test4();
}

Implementation of interface.
When we implement interface, we have to write implementation of all the methods in child
class.
public interface Example1 {
public final static int i=90;
int j =80;

public void test1();


public void test2();
public void test3();

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public void test4();
}

public class TestInterface implements Example1{

@Override
public void test1() {
// TODO Auto-generated method stub

@Override
public void test2() {
// TODO Auto-generated method stub

@Override
public void test3() {
// TODO Auto-generated method stub

@Override
public void test4() {
// TODO Auto-generated method stub

Real Time Example of Interface

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package constructorsInjava;

public interface RateOfInterest {

public void rateofInterest();

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package constructorsInjava;

public class SBI implements RateOfInterest{

@Override
public void rateofInterest() {
System.out.println("SBI gives 6 %");
}
}

package constructorsInjava;

public class HDFC implements RateOfInterest{

@Override
public void rateofInterest() {
System.out.println("HDFC gives 7 %");
}
}

package constructorsInjava;

public class AXIS implements RateOfInterest{

@Override
public void rateofInterest() {
System.out.println("AXIS gives 7 %");
}
}

package constructorsInjava;

public class TestInterface {

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public static void main(String[] args) {
SBI sbi = new SBI();
HDFC hdfc = new HDFC();
AXIS axis = new AXIS();
sbi.rateofInterest();
hdfc.rateofInterest();
axis.rateofInterest();
}
}

Out Put:
SBI gives 6 %
HDFC gives 7 %
AXIS gives 7 %

Real Time Example of Interface

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Multiple inheritance through interface example.

In Interface, we can inheritance multiple interface by writing interface as comma separated


after implements keyword.
This is not possible in case of inheritance. We cannot write inheritance as comma separated
after extends keyword.

public interface A {
public void test1();
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public interface B {
public void test2();
}

public interface C {
public void test3();
}

public class TestMultipleInheritanceOfInterface implements A,B,C{

@Override
public void test3() {
// TODO Auto-generated method stub

@Override
public void test2() {
// TODO Auto-generated method stub

@Override
public void test1() {
// TODO Auto-generated method stub

Why Default Methods in Interfaces Are Needed

Like regular interface methods, default methods are implicitly public — there’s no need to
specify the public modifier.
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Unlike regular interface methods, they are declared with the default keyword at the
beginning of the method signature, and they provide an implementation.
The reason why default methods were included in the Java 8 release is pretty obvious.
In a typical design based on abstractions, where an interface has one or multiple
implementations, if one or more methods are added to the interface, all the
implementations will be forced to implement them too. Otherwise, the design will just
break down.
Default interface methods are an efficient way to deal with this issue. They allow us to add
new methods to an interface that are automatically available in the implementations.
Thus, there’s no need to modify the implementing classes.
In this way, backward compatibility is neatly preserved without having to refactor the
implementers.

package interfaceInJava;

/**
Why Default Methods in Interfaces Are Needed

Like regular interface methods, default methods are implicitly public


there’s no need to specify the public modifier.
Unlike regular interface methods, they are declared with the default
keyword at the beginning of the method signature, and they provide an implementation.
*/
public interface Vehicle1 {

String getBrand();

String speedUp();

String slowDown();

default String turnAlarmOn() {


int a = 90;
int b = 100;
int c= a+b;
return "Turning the vehicle alarm on.";
}

default String turnAlarmOff() {

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
return "Turning the vehicle alarm off.";
}
}

package interfaceInJava;

public class Car1 implements Vehicle1{

@Override
public String getBrand() {
// TODO Auto-generated method stub
return null;
}

@Override
public String speedUp() {
// TODO Auto-generated method stub
return null;
}

@Override
public String slowDown() {
// TODO Auto-generated method stub
return null;
}

public static void main(String[] args) {


Car1 obj = new Car1();
// here we can call methods of interface without
// implementing
obj.turnAlarmOff();
obj.turnAlarmOn();
obj.getBrand();
}

Static Interface Methods

Aside from being able to declare default methods in interfaces, Java 8 allows us to define
and implementstatic methods in interfaces.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Since static methods don’t belong to a particular object, they are not part of the API of the
classes implementing the interface, and they have to be called by using the interface name
preceding the method name.

package interfaceInJava;

/**
Static Interface Methods
Java 8 allows us to define and implement static methods in interfaces.

Since static methods don’t belong to a particular object, they are not part of
the API of the classes implementing the interface,
and they have to be called by using the interface name preceding the method name.
*/
public interface Vehichle3 {

void spped();
void gear();

static int getHorsePower(int rpm, int torque) {


return (rpm * torque) / 5252;
}
}

package interfaceInJava;

public class Car2 implements Vehichle3{

@Override
public void spped() {
}

@Override
public void gear() {
}

public static void main(String[] args) {


Car2 obj = new Car2();
obj.spped();
obj.gear();
// static method of interface we can call through interface
int i = Vehichle3.getHorsePower(30000, 20);
System.out.println(i);

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Vehichle3 obj1 = new Car2();
// when we create object of interface we will get compile time error
//Vehichle3 obj2 = new Vehichle3();
}
}

Abstract Class in Java

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
· Abstract class will have implemented and un-implemented methods.
· We Cannot create object of Abstract class.
· We Can write constructor in Abstract class.

· To make class Abstract class we need to have at least one method as Abstract method.
· We can create Reference of Abstract class and object of child class.

Basic Structure

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Abstract class can have both implemented and non-implemented methods

package abstractInJava;

public abstract class Example1 {

// constructor of class
Example1() {
}

// parameterized constructor of class


Example1(int i) {
}

// default access member of class


int i = 90;
// public access member of class
public int j = 80;
// abstract method
abstract void test1();

abstract void test3();


// implemented method
void test2() {
System.out.println("abstract method");
}
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public abstract class ExampleAbstarct1 {

public abstract void test1();

// implemented method
public void test2(){
System.out.println("I am implmented method test2() from abstract class");
}
public void test3(){
System.out.println("I am implmented method test3() from abstract class");
}
// non-implemented method
public abstract void test4();
// non-implemented method
abstract void test5();
}

public class TestAbstractClass extends ExampleAbstarct1{

@Override
public void test1() {
System.out.println("I am from child class implementation test1() ");
}

@Override
public void test4() {
System.out.println("I am from child class implementation test4()");
}

// here by default access are not public. Whatever abstract class method access has
// same will be retained by concrete class
@Override
void test5() {

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
System.out.println("I am from child class implementation ttest5() ");
}

public static void main(String[] args) {


ExampleAbstarct1 obj = new TestAbstractClass();
obj.test1();
obj.test2();
obj.test3();
obj.test4();
obj.test5();
}
}

Out put
I am from child class implementation test1()
I am implemented method test2() from abstract class
I am implemented method test3() from abstract class
I am from child class implementation test4()
I am from child class implementation ttest5()

When abstract class extends other abstract class, it is not necessary to write
implementation of unimplemented method. If we want we can write selected method.

Example
package abstractInJava;

public abstract class Example1 {

// constructor of class
Example1() {
}

// parameterized constructor of class


Example1(int i) {
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// default access member of class
int i = 90;
// public access member of class
public int j = 80;
// abstract method
abstract void test1();

abstract void test3();


// implemented method
void test2() {
System.out.println("abstract method");
}
}

package abstractInJava;

/**
* Example3 is not writing implementation of all
* unimplemented method of Example1
*/
public abstract class Example3 extends Example1{

void test1(){
System.out.println("Example3 implements test1()");
}
}

Use of Abstract Class

package abstractInJava;

public abstract class Person {

// two abstract class members


private String name;
private String gender;

// parameterized constructor
Person(String name, String gender){
this.name = name;
this.gender = gender;
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// abstract method
abstract void work(int id);

// implemented method
public void changeName(String newName){
name = newName;
}

// Override toString() method to print object Data


@Override
public String toString() {
return "Person [name=" + name + ", gender=" + gender + "]";
}

package abstractInJava;

public class TestPerson extends Person{

int id;
// parameterized constructor
TestPerson(String name, String gender, int id){
// super will call Person abstract class constructor
super(name,gender);
this.id = id;
}

@Override
void work(int id) {
if(id == 0){
System.out.println("person is not working");
}
else{
System.out.println("person is woring");
}
}

public static void main(String[] args) {


TestPerson obj = new TestPerson("Bhanu","M",100);
obj.work(obj.id);

TestPerson obj1 = new TestPerson("Bhanu1","M",0);


obj1.work(obj1.id);

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
// call changeName from abstract class
obj.changeName("Test1");
// when we print obj toString() method will get called
System.out.println(obj);
// when we print obj1 toString() method will get called
System.out.println(obj1);
}

Output:
person is woring
person is not working
Person [name=Test1, gender=M]
Person [name=Bhanu1, gender=M]

In country abstract class Nationality will not change for any person. But Name and gender
will change based on individual.
So we can make implemented method called getNationality() and abstract method as
getName() and getGender()

Example
package abstractInJava;

public abstract class Country {

public String getNationality(){


return "Indian";
}

abstract public String getName();

abstract public String getGender();

package abstractInJava;

public class Person1 extends Country{

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
String name;
String gender;

Person1(String name, String gender){


this.name = name;
this.gender = gender;
}

@Override
public String getName() {
return name;
}

@Override
public String getGender() {
return gender;
}

public void display(){


System.out.println("Name is:"+getName()+" gender is: "+getGender() + "
nationality is: "+getNationality());
}

public static void main(String[] args) {


Person1 obj = new Person1("test1","M");
obj.display();
Person1 obj1 = new Person1("test2","F");
obj1.display();
}

Output:
Name is:test1 gender is: M nationality is: Indian
Name is:test2 gender is: F nationality is: Indian

The key technical differences between an abstract class and an interface are:

o Methods and members of an abstract class can be defined with any visibility, whereas all
methods of an interface must be defined as public (they are defined public by default).

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
o When inheriting an abstract class, a concrete child class must define the abstract
methods, whereas an abstract class can extend another abstract class and abstract
methods from the parent class don't have to be defined.
o Similarly, an interface extending another interface is not responsible for implementing
methods from the parent interface. This is because interfaces cannot define any
implementation.
o A child class can only extend a single class (abstract or concrete), whereas an interface
can extend or a class can implement multiple other interfaces.

o A child class can define abstract methods with the same or less restrictive visibility,
whereas a class implementing an interface must define the methods with the exact
same visibility (public)

Methods and members of an abstract class can be defined with any visibility, whereas all
methods of an interface must be defined as public (they are defined public by default).

Here we are creating abstract class with all access type except private.

public abstract class ExampleAbstarct1 {

public abstract void test1();


protected abstract void test4();
abstract void test5();
}

When we extend by concrete class, by default all the access will not be public

public class TestAbstractClass extends ExampleAbstarct1{

@Override
public void test1() {
// TODO Auto-generated method stub

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
}

@Override
protected void test4() {
// TODO Auto-generated method stub

}
// here by default access are not public
@Override
void test5() {
// TODO Auto-generated method stub

Here we are creating interface class with all access type except private.

public interface Example1 {

public void test1();


void test2();

// When we try to create method with protected access we will get compile time
error.
// Since by default access of methodsa are public
protected void test3();
}

When we implement interface by default child class will get all method access as public. If
we try to change access type, we will get compile time error.

public class TestInterface implements Example1{

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
@Override
public void test1() {
// TODO Auto-generated method stub

@Override
public void test2() {
// TODO Auto-generated method stub

When inheriting an abstract class, a concrete child class must define the abstract methods,
whereas an abstract class can extend another abstract class and abstract methods from
the parent class don't have to be defined.

When we extend one abstract class from other abstract class we don’t need to implement
the abstract methods.
Same is not applicable when we extend from concrete class. Concrete class has to
implement all unimplemented methods.

public abstract class AbstarctClass1 {

public abstract void test1();


public abstract int test2();
public abstract void test3();

public abstract class AbstarctClass2 extends AbstarctClass1{

Concrete class has to implement all unimplemented methods. If we will not implement all
unimplemented methods, then we will get compile time error.

public class ConcreteClass extends AbstarctClass1{

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
@Override
public void test1() {
// TODO Auto-generated method stub

@Override
public int test2() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void test3() {
// TODO Auto-generated method stub

When Interface extends other interface then method implementation by another


interface is not required. Since interface cannot have implemented method

Point to remember:
• Interface extends interface.
• Class implements interface

public interface Interface1 {

public void test1();


public void test2();
public void test3();
}

public interface Interface2 extends Interface1{

// Here Class has to implement all the unimplemented methods of interface


public class ConcreteClass implements Interface1{

@Override
Author: Bhanu Pratap Singh.
Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
public void test1() {
// TODO Auto-generated method stub

@Override
public void test2() {
// TODO Auto-generated method stub

@Override
public void test3() {
// TODO Auto-generated method stub

Instance Initializer block

• Instance Initializer block use to initialized instance data member of class. IIB will get
executed per object. The initialization of the instance variable can be done directly
but there can be performed extra operations while initializing the instance variable
in the instance initializer block.

• IIB will get executed per object.


• If we have 5 objects of class, IIB will get executed 5 times.

What is the use of instance initializer block while we can directly assign a value in instance
data member?

Direct data initialization without IIB

package iib;

public class Example1 {


int runspeed = 100;
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
IIB Example

package iib;

public class Example2 {

int speed;

Example2() {
System.out.println("speed is " + speed);
}

{
speed = 100;
}

public static void main(String args[]) {


Example2 b1 = new Example2();
Example2 b2 = new Example2();
}
}

Output:
speed is 100
speed is 100

Use of IIB.

Let’s say we want for loop to fill a complex array before object creation. Which we can
achieve through IIB

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package iib;

public class Example3 {

int a[];

{
a = new int[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
}
}

void display(){
System.out.print("[");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.print("]");
}

public static void main(String[] args) {


Example3 obj = new Example3();

obj.display();
}

Output: [0 1 2 3 4 5 6 7 8 9]

If we have 3 objects of class, IIB will get executed 3 times.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package iib;

public class Example4 {

{
System.out.println("I am IIB first");
}

{
System.out.println("I am IIB second");
}

public static void main(String[] args) {


Example4 obj = new Example4();
System.out.println("---------");
Example4 obj1 = new Example4();
System.out.println("---------");
Example4 obj2 = new Example4();
}
}

Output:
I am IIB first
I am IIB second
---------
I am IIB first
I am IIB second
---------
I am IIB first
I am IIB second

Rules for instance initializer block:

There are mainly three rules for the instance initializer block. They are as follows:
• The instance initializer block is created when instance of the class is created.
• The instance initializer block is invoked after the parent class constructor is invoked
(i.e. after super() constructor call).
• The instance initializer block comes in the order in which they appear.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
The instance initializer block is invoked after the parent class constructor is invoked (i.e.
after super () constructor call).

package iib;

public class Example5 {

Example5(){
System.out.println("Parent class
constructor");
}

{
System.out.println("Super IIB");
}
}

package iib;

public class Example6 extends Example5{

{
System.out.println("Child IIB");
}

public static void main(String[] args) {


Example6 obj = new Example6();
}
}

Output:

Super IIB
Parent class constructor
Child IIB

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
The instance initializer block comes in the order in which they appear.

package iib;

public class Example7 {

{
System.out.println("I am first IIB");
}
{
System.out.println("I am second IIB");
}
{
System.out.println("I am third IIB");
}

public static void main(String[] args) {


Example7 obj = new Example7();
}

Output:
I am first IIB
I am second IIB
I am third IIB

Final Keyword in Java

• Final keyword is used to restrict the user to change the implementation of method
or change the initialized value of variable.

• A final variable that have no value it is called blank final variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final variable can be
static also which will be initialized in the static block only.

• Final variable cannot be blank.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Final is applicable for
A. Variable.
B. Method.
C. Class.

If you make any variable as final, you cannot change the value of final variable (It will be
constant).

package finalInJava;

public class Example1 {

final int k = 10;

void test1(){
// when I try to change the value of final
// I will get compile time error.
k = 20;
System.out.println(k);
}

public static void main(String[] args) {


Example1 obj = new Example1();
obj.test1();
}

Final method implementation cannot be changed.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package finalInJava;

public class Example2 {

final public void test(){


System.out.println("Example2");

package finalInJava;

public class Example3 extends Example2{

// when we try to change the implementation of


parent class
// final method we will see compile time error.
public void test(){
int sum = 2+3;
System.out.println(sum);

If you make any class as final, you cannot extend it.

package finalInJava;

final public class Example4 {

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package finalInJava;

//when we try to extends final class we will get


//compile time error
public class Example5 extends Exanple4{

Q: Is final method inherited?

Answer: Yes, final method is inherited but you cannot override it.

Example:
package finalInJava;

public class Example6 {


final void run() {
System.out.println("running...");
}
}

package finalInJava;

public class Example7 {


public static void main(String args[]) {
new Example6().run();
}
}

A final variable that have no value it is called blank final variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final variable can be static
also which will be initialized in the static block only.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package finalInJava;

public class Example8 {

final int k;

final static int i;

// non static final is initialized in constructor


Example8(){
k = 90;
}

// non static final is initialized in static block


static {
i = 90;
}

public static void main(String[] args) {

Final variable cannot be blank.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package finalInJava;

public class Example9 {

// will get compile time error. since


// final variable should get initialized
final int k;

// if variable is not final we will not get compile


time error.
int j;

Q: Can we declare a constructor final?

No, because constructor is never inherited.

Java instanceof operator.

The java instance of operator is used to test whether the object is an instance of class,
subclass or interface

Example:

package instanceOfOperator;

public class Example1 {


public static void main(String args[]) {
Example1 s = new Example1();
System.out.println(s instanceof Example1);//
true
}
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Example:

package instanceOfOperator;

public class A {

package instanceOfOperator;

public class B extends A {

public static void main(String[] args) {


B obj = new B();
System.out.println(obj instanceof A);// true
}

Example

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package instanceOfOperator;

public class C {

public static void main(String[] args) {


String s1 = "test";
System.out.println(s1 instanceof String);
//true

Encapsulation in Java

Encapsulation in java is a process of binding code and data together into a single unit

We can create a fully encapsulated class in java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

Example1

package encapsulation;

public class Example1 {

private int age;

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
Advantage of Encapsulation in java

• By providing only setter or getter method, you can make the class read-only or write-
only.
• We can provide data security.

Example2:
package encapsulation;

public class Example2 {

private int age;

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package encapsulation;

public class Example3 {

public static void main(String[] args) {

Example2 obj = new Example2();


obj.setAge(50);
System.out.println(obj.getAge());

// if we don't set age and try to get the age


// will get 0 as output.
Example2 obj1 = new Example2();
System.out.println(obj1.getAge());
}

Output:
50
0

Example:

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package encapsulation;

public class Example4 {


private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge(int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum(String newId) {


idNum = newId;
}
}

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package encapsulation;

public class Example5 {


public static void main(String args[]) {
Example4 obj = new Example4();
obj.setName("Bhanu");
obj.setAge(20);
obj.setIdNum("143ms");

System.out.print("Name : " + obj.getName() + "


Age : " + obj.getAge());
}
}

Output:

Name : Bhanu Age : 20

Static Block in Java

Static Block. Static block is used for initializing the static variables. This block gets executed
when the class is loaded in the memory. A class can have multiple Static blocks, which will
execute in the same sequence in which they have been written into the program.

Static block execution does not depend on object creation.

Example:

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package staticBlockinJava;

public class Example1 {

static int num;


static String mystr;
static {
num = 97;
mystr = "Static keyword in Java";
}

public static void main(String args[]) {


System.out.println("Value of num: " + num);
System.out.println("Value of mystr: " +
mystr);
}
}

Output:
Value of num: 97
Value of mystr: Static keyword in Java

Example:

Static block execution does not depend on object creation.

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/
package staticBlockinJava;

public class Example2 {

static {
System.out.println("I am SIB one");
}

static {
System.out.println("I am SIB two");
}

static {
System.out.println("I am SIB three");
}

public static void main(String[] args) {

Output:
I am SIB one
I am SIB two
I am SIB three

Author: Bhanu Pratap Singh.


Native: Muzaffarpur Bihar.
https://www.facebook.com/learnbybhanupratap/
https://www.udemy.com/javabybhanu
https://www.udemy.com/seleniumbybhanu/

You might also like