Oops in Java - 5
Oops in Java - 5
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.
Vehicle:
Animal: -
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)
Object Reference will be created into stack Area where as Object will be created in heap
Area
• 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
• fields
• methods
• constructors
• blocks
• nested class and interface
Example2:
package com.coreJava;
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.
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.
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.
These variable should not be preceded by any These variables are preceded by static
static keyword Example: keyword.
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.
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.
Note: static variable not only can be access with class reference but also some time it can be
accessed with object reference.
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;
• 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
package staicAndNonStatic;
// 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;
// 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);
}
// 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";
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.
Constructor in Java
Types of Constructor:
Constructor
Default(No arg
Parameterized
constructor)
Syntax:
package constructorInjava;
Output:
I am Test1()
I am Test1(int a, int b)
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;
Use of Constructor
Answer: Yes
package constructorInjava;
}
// Constructor with two argument
Example3(int i, int j) {
}
// Constructor with three argument
Example3(int i, int j, int k) {
package constructorInjava;
Output:
I am Example4()
I am Example4(int i, int j)
I am Example4(int i, int j, int k)
package constructorInjava;
Output:
2
8
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;
• 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()
Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
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.
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.
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.
Same Class
package modifier;
// Instance variable
public int i = 10;
int j = 20;
protected int k = 30;
private int p = 40;
package modifier;
package testModifier;
import modifier.Example1;
package testModifier;
import modifier.Example1;
System.out.println(obj.i);
System.out.println(obj.k);
}
}
This in Java
This is java keyword. It(this) works as a reference to the current Object.
package thisInjava;
int i;
int 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
*/
package thisInjava;
int i;
int j;
int k;
// here we don't need this keyword. since instance and local variable is different
Example2(int i){
k = i;
}
Output
5
6
5
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);
}
}
}
/**
Output
default constructor
value of i is: 5
value of i is: 5 and value of k is: 6
*/
package thisInjava;
Output
test2
test1
package thisInjava;
test1
thisInjava.Example5@7852e922
test1
thisInjava.Example5@4e25154f
*/
package thisInjava;
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;
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();
}
Output:
value of i is:90
package thisInjava;
int i = 90;
package thisInjava;
int i = 90;
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.
• 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.
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
package methodOverloading;
package methodOverloading;
package methodOverloading;
/**
add(double d1, double d2)
add(int i, int j)
*/
package methodOverloading;
}
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;
}
// overloaded method with same argument but different return type.
// we will get compile time error.
public int test(int i) {
return i;
}
}
package methodOverloading;
// 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/
}
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;
// 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)");
}
/**
* 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)");
}
package methodOverloading;
On Run Time Method call happens based on the parameters supplied to method
// 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.
When we create object of child class, child class object will get all members of parent class
and child class.
package inherinatnceInJava;
package inherinatnceInJava;
/**
* To use inheritance we have to use "extends" keyword
*/
public class ChildClass extends ParentClass{
Output:
I am from Parent class test1()
I am from Parent class test2()
package inherinatnceInJava;
/**
* To use inheritance we have to use "extends" keyword
*/
public class ChildClass1 extends ParentClass1{
Output:
I am from child1 class Test3()
I am from Parent1 class test1()
I am from Parent1 class test2()
• 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;
// 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()");
}
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{
/**
* 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
// default constructor
ParentClass3() {
System.out.println("ParentClass3()");
}
// parameterized constructor
ParentClass3(int i) {
System.out.println("ParentClass3(int i) ");
}
}
package inherinatnceInJava;
package inherinatnceInJava;
package inherinatnceInJava;
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 {
package inherinatnceInJava;
/**
* Here B is child class and A is parent class
*/
public class C extends B {
Output:
A
B
C
90
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.
public class A {
void test() {
System.out.println("Welcome");
}
}
package inheritance;
public class B {
void test() {
System.out.println("Welcome");
}
}
package inheritance;
Output:
Compile time error.
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.
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.
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;
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{
Output:
color is: black
color is: white
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;
package superInJava;
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
package superInJava;
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{
Output:
I am run method from child class
I am run method from parent class
I am test method from parent class
package inherinatnceInJava;
// 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;
}
package inherinatnceInJava;
// 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;
}
package inherinatnceInJava;
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
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.
public class G {
G(int i) {
System.out.println("G(int i)");
}
G() {
System.out.println("G()");
}
package superKeywordInJava;
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.
public class I {
I() {
System.out.println("I");
}
package superKeywordInJava;
J() {
// Here Java compiler will keep super () by
default when we do not write.
System.out.println("J");
}
System.out.println("J");
}
Output:
I
J
package superKeywordInJava;
void display() {
System.out.println("id: "+id + " name: " +
name + " salary: " + salary);
}
obj.display();
}
Points to Remembers:
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.
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.
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.
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.
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.
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.
package methodOverridding;
package methodOverridding;
/**
* To override parent class method need to extends parent class
*/
public class Example2 extends Example1{
// Overridden method
public void test(){
Output:
I am from Example2 child class
package methodOverridding;
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");
}
// Overridden method
public void test(){
System.out.println("I am from Example3 child class");
}
package methodOverridding;
package methodOverridding;
Output:
I am from Example2 child class
I am from Example3 child class
I am from Example1 parent class
package methodOverridding;
package methodOverridding;
package methodOverridding;
// Overridden method
void sendMessage(){
System.out.println("Samsung message");
}
}
package methodOverridding;
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;
package methodOverridding;
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{
Output:
from A
package methodOverridding;
public class A {
public void test(int a, double b){
System.out.println("from A");
}
}
package methodOverridding;
package methodOverridding;
public class C {
package methodOverridding;
package methodOverridding;
public class C {
// method with integer type return type
int test1(){
System.out.println("test1() from C");
return 5;
}
}
package methodOverridding;
Output:
test1() from D
Interface in Java
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;
@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
@Override
public void rateofInterest() {
System.out.println("SBI gives 6 %");
}
}
package constructorsInjava;
@Override
public void rateofInterest() {
System.out.println("HDFC gives 7 %");
}
}
package constructorsInjava;
@Override
public void rateofInterest() {
System.out.println("AXIS gives 7 %");
}
}
package constructorsInjava;
Out Put:
SBI gives 6 %
HDFC gives 7 %
AXIS gives 7 %
public interface A {
public void test1();
}
public interface C {
public void test3();
}
@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
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
String getBrand();
String speedUp();
String slowDown();
package interfaceInJava;
@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;
}
Aside from being able to declare default methods in interfaces, Java 8 allows us to define
and implementstatic methods in interfaces.
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();
package interfaceInJava;
@Override
public void spped() {
}
@Override
public void gear() {
}
· 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
package abstractInJava;
// constructor of class
Example1() {
}
// 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();
}
@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() {
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;
// constructor of class
Example1() {
}
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()");
}
}
package abstractInJava;
// parameterized constructor
Person(String name, String gender){
this.name = name;
this.gender = gender;
}
// implemented method
public void changeName(String newName){
name = newName;
}
package abstractInJava;
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");
}
}
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;
package abstractInJava;
@Override
public String getName() {
return name;
}
@Override
public String getGender() {
return gender;
}
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).
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.
When we extend by concrete class, by default all the access will not be public
@Override
public void test1() {
// TODO Auto-generated method stub
@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.
// 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.
@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.
Concrete class has to implement all unimplemented methods. If we will not implement all
unimplemented methods, then we will get compile time error.
@Override
public int test2() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void test3() {
// TODO Auto-generated method stub
Point to remember:
• Interface extends interface.
• Class implements interface
@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 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.
What is the use of instance initializer block while we can directly assign a value in instance
data member?
package iib;
package iib;
int speed;
Example2() {
System.out.println("speed is " + speed);
}
{
speed = 100;
}
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
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("]");
}
obj.display();
}
Output: [0 1 2 3 4 5 6 7 8 9]
{
System.out.println("I am IIB first");
}
{
System.out.println("I am IIB second");
}
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
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.
package iib;
Example5(){
System.out.println("Parent class
constructor");
}
{
System.out.println("Super IIB");
}
}
package iib;
{
System.out.println("Child IIB");
}
Output:
Super IIB
Parent class constructor
Child IIB
package iib;
{
System.out.println("I am first IIB");
}
{
System.out.println("I am second IIB");
}
{
System.out.println("I am third IIB");
}
Output:
I am first IIB
I am second IIB
I am third IIB
• 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.
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
package finalInJava;
void test1(){
// when I try to change the value of final
// I will get compile time error.
k = 20;
System.out.println(k);
}
package finalInJava;
package finalInJava;
Answer: Yes, final method is inherited but you cannot override it.
Example:
package finalInJava;
package finalInJava;
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 int k;
The java instance of operator is used to test whether the object is an instance of class,
subclass or interface
Example:
package instanceOfOperator;
package instanceOfOperator;
public class A {
package instanceOfOperator;
Example
public class C {
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;
• 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;
Output:
50
0
Example:
Output:
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.
Example:
Output:
Value of num: 97
Value of mystr: Static keyword in Java
Example:
static {
System.out.println("I am SIB one");
}
static {
System.out.println("I am SIB two");
}
static {
System.out.println("I am SIB three");
}
Output:
I am SIB one
I am SIB two
I am SIB three