Classes and Objects
What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
oFields
oMethods
oConstructors
oBlocks
oNested class and interface
Syntax to declare a class:
class <class_name>
{
field;
method;
}
Instance variable in Java
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Compile by: javac Student.java
Run by: java Student
0
null
Object and Class Example: main outside the class
In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Compile by: javac TestStudent1.java
Run by: java TestStudent1
0
null
3 Ways to initialize object
There are 3 ways to initialize object in Java.
1.By reference variable
2.By method
3.By constructor
1)Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Compile by: javac TestStudent2.java
Run by: java TestStudent2
101 Sonoo
Types of inheritance in java
What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
oFields
oMethods
oConstructors
oBlocks
oNested class and interface
Syntax to declare a class:
class <class_name>
{
field;
method;
}
Instance variable in Java
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
Object and Class Example: main within the class
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Compile by: javac Student.java
Run by: java Student
0
null
Object and Class Example: main outside the class
In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Compile by: javac TestStudent1.java
Run by: java TestStudent1
0
null
3 Ways to initialize object
There are 3 ways to initialize object in Java.
1.By reference variable
2.By method
3.By constructor
1)Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Compile by: javac TestStudent2.java
Run by: java TestStudent2
101 Sonoo
2)Object
and Class Example: Initialization through method
In
this example, we are creating the two objects of Student class and initializing
the value to these objects by invoking the insertRecord method. Here, we are
displaying the state (data) of the objects by invoking the displayInformation()
method.
class
Student
{
int
rollno;
String
name;
void
insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void
displayInformation()
{
System.out.println(rollno+"
"+name);
}
}
class
TestStudent4
{
public
static void main(String args[]){
Student
s1=new Student();
Student
s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Compile
by: javac TestStudent4.java
Run
by: java TestStudent4
111
Karan
222
Aryan
3)Object
and Class Example: Initialization through a constructor
class
Employee
{
int
id;
String
name;
float
salary;
void
insert(int i, String n, float s)
{
id=i;
name=n;
salary=s;
}
void
display()
{
System.out.println(id+"
"+name+" "+salary);
}
}
public
class TestEmployee
{
public
static void main(String[] args)
{
Employee
e1=new Employee();
Employee
e2=new Employee();
Employee
e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
Output:
101
ajeet 45000.0
102
irfan 25000.0
103
nakul 55000.0
Object
and Class Example: Rectangle
class
Rectangle
{
int
length;
int width;
void
insert(int l, int w)
{
length=l;
width=w;
}
void
calculateArea()
{
System.out.println(length*width);
}
}
class
TestRectangle1
{
public
static void main(String args[])
{
Rectangle
r1=new Rectangle();
Rectangle
r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
Output:
55
45
Anonymous
object
Anonymous
simply means nameless. An object which has no reference is known as an
anonymous object. It can be used at the time of object creation only.
If
you have to use an object only once, an anonymous object is a good approach.
For example:
1.new
Calculation();//anonymous object
Calling
method through a reference:
1.Calculation
c=new Calculation();
2.c.fact(5);
Calling
method through an anonymous object
1.new
Calculation().fact(5);
class
Calculation
{
void
fact(int n)
{
int
fact=1;
for(int
i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factorial
is "+fact);
}
public
static void main(String args[])
{
new
Calculation().fact(5);//calling method with anonymous object
}
}
Output:
Factorial
is 120
Constructors
in Java
It
is a special type of method which is used to initialize the object.
Every
time an object is created using the new() keyword, at least one constructor is
called.
Rules
for creating Java constructor
There
are two rules defined for the constructor.
1.Constructor
name must be the same as its class name
2.A
Constructor must have no explicit return type
3.A
Java constructor cannot be abstract, static, final, and synchronized
We
can use access modifiers while declaring a constructor. It controls the object
creation. In other words, we can have private, protected, public or default
constructor in Java.
Types
of Java constructors
There
are two types of constructors in Java:
1.Default
constructor (no-arg constructor)
2.Parameterized
constructor
Java
Default Constructor
A
constructor is called "Default Constructor" when it doesn't have any
parameter.
Syntax
of default constructor:
1.<class_name>(){}
//Java
Program to create and call a default constructor
class
Bike1
{
//creating
a default constructor
Bike1(){System.out.println("Bike
is created");
}
//main
method
public
static void main(String args[])
{
//calling
a default constructor
Bike1
b=new Bike1();
}
}
Output:-Bike
is created
Java Parameterized Constructor
A
constructor which has a specific number of parameters is called a parameterized
constructor.
Why use the parameterized
constructor?
The
parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
//Java
Program to demonstrate the use of the parameterized constructor.
class
Student4
{
int id;
String
name;
//creating
a parameterized constructor
Student4(int
i,String n)
{
id
= i;
name
= n;
}
//method
to display the values
void
display()
{
System.out.println(id+"
"+name);
}
public static void main(String args[])
{
//creating
objects and passing values
Student4
s1 = new Student4(111,"Karan");
Student4
s2 = new Student4(222,"Aryan");
//calling
method to display the values of object
s1.display();
s2.display();
}
}
Output:
111
Karan
222
Aryan
Does constructor return any value?
Yes,
it is the current class instance (You cannot use return type yet it returns a
value).
Can constructor perform other tasks
instead of initialization?
Yes,
like object creation, starting a thread, calling a method, etc. You can perform
any operation in the constructor as you perform in the method.
Is there Constructor class in Java?
Yes.
Inheritance in Java
Inheritance
in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The
idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new methods
and fields in your current class also.
Inheritance
represents the IS-A relationship which is also known as a parent-child
relationship.
Why
use inheritance in java
oFor
Method Overriding (so runtime polymorphism can be achieved).
oFor
Code Reusability.
Terms used in Inheritance
oClass:
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
oSub
Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
oSuper
Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
oReusability:
As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class
Subclass-name extends Superclass-name
{
//methods and fields
}
The
extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the
functionality.
Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.
Types of inheritance in java
Single
Inheritance in Java with Example
Inheritance
is one of the key features of object-oriented programming (OOP).Single
Inheritance enables a derived class(Sub class) to inherit properties and
behavior from a single parent class(Super class). When a class extends another
one class only then we call it a single
inheritance.
public
class Shape
{
int
length;
int
breadth;
}
public
class Rectangle extends Shape
{
int
area;
public
void calcualteArea()
{
area
= length*breadth;
}
public
static void main(String args[])
{
Rectangle
r = new Rectangle();
//Assigning
values to Shape class attributes
r.length
= 10;
r.breadth
= 20;
//Calculate
the area
r.calcualteArea();
System.out.println("The
Area of rectangle of length \""
+r.length+"\"
and breadth \""+r.breadth+"\" is
\""+r.area+"\"");
}
}
Output
:
The
Area of rectangle of length "10" and breadth "20" is
"200"
Multiple
Inheritance in Java Example
Multiple
Inheritance in Java is nothing but one class extending more than one class.
Java does not have this capability. As the designers considered that multiple
inheritance will to be too complex to manage, but indirectly you can achieve
Multiple Inheritance in Java using Interfaces.
Multiple
Inheritance” refers to the concept of one class extending (Or inherits) more
than one base class. Here we have two interfaces Car and Bus.
•Car
interface has a attribute speed and a method defined distanceTravelled()
•Bus
interface has a attribute distance and method speed()
The
Vehicle class implements both interface Car and Bus and provides
implementation.
interface
Car
{
int speed=60;
public
void distanceTravelled();
}
interface
Bus
{
int
distance=100;
public
void speed();
}
public
class Vehicle implements Car,Bus
{
int
distanceTravelled;
int
averageSpeed;
public
void distanceTravelled()
{
distanceTravelled=speed*distance;
System.out.println("Total
Distance Travelled is : "+distanceTravelled);
}
public
void speed()
{
int
averageSpeed=distanceTravelled/speed;
System.out.println("Average
Speed maintained is : "+averageSpeed);
}
public
static void main(String args[])
{
Vehicle
v1=new Vehicle();
v1.distanceTravelled();
v1.speed();
}
}
Output
:
Total
Distance Travelled is : 6000
Average
Speed maintained is : 100
Multilevel
Inheritance in Java with Example
In
Java Multilevel Inheritance sub class will be inheriting a parent class and as
well as the sub class act as the parent class to other class
When
a class extends a class, which extends anther class then this is called
multilevel inheritance.
Class
X
{
public
void methodX()
{
System.out.println("Class
X method");
}
}
Class
Y extends X
{
public
void methodY()
{
System.out.println("class
Y method");
}
}
Class
Z extends Y
{
public
void methodZ()
{
System.out.println("class
Z method");
}
public
static void main(String args[])
{
Z
obj = new Z();
obj.methodX();
//calling grand parent class method
obj.methodY();
//calling parent class method
obj.methodZ();
//calling local method
}
}
Hierarchical Inheritance:-In such kind of
inheritance one class is inherited by many sub classes
class
A
{
public
void methodA()
{
System.out.println("method
of Class A");
}
}
class
B extends A
{
public
void methodB()
{
System.out.println("method
of Class B");
}
}
class
C extends A
{
public
void methodC()
{
System.out.println("method
of Class C");
}
}
class
D extends A
{
public
void methodD()
{
System.out.println("method
of Class D");
}
}
class
JavaExample
{
public
static void main(String args[])
{
B
obj1 = new B();
C
obj2 = new C();
D
obj3 = new D();
//All
classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
method
of Class A
method
of Class A
method
of Class A
Hybrid Inheritance
In
simple terms you can say that Hybrid inheritance is a combination of Single and
Multiple inheritance.
class
C
{
public
void disp()
{
System.out.println("C");
}
}
class
A extends C
{
public
void disp()
{
System.out.println("A");
}
}
class
B extends C
{
public
void disp()
{
System.out.println("B");
}
}
class
D extends A
{
public
void disp()
{
System.out.println("D");
}
public
static void main(String args[]){
D
obj = new D();
obj.disp();
}
}
Output:
D
Interface in Java
An
interface in java is a blueprint of a class. It has static constants and
abstract methods.
The
interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
In
other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Java
Interface also represents the IS-A relationship.It cannot be instantiated just
like the abstract class.
Since
Java 8, we can have default and static methods in an interface.Since Java 9, we
can have private methods in an interface.
Why use Java interface?
There
are mainly three reasons to use interface. They are given below.
oIt
is used to achieve abstraction.
oBy
interface, we can support the functionality of multiple inheritance.
oIt
can be used to achieve loose coupling.
How to declare an interface?
An
interface is declared by using the interface keyword. It provides total
abstraction; means all the methods in an interface are declared with the empty
body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the
interface.
Eg.
Multiple inheritance(see above)
Abstraction in Java
Abstraction
is a process of hiding the implementation details and showing only
functionality to the user.
Ways
to achieve Abstraction
There
are two ways to achieve abstraction in java
1.Abstract
class (0 to 100%)
2.Interface
(100%)
Abstract class in Java
A
class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
Points
to Remember
oAn
abstract class must be declared with an abstract keyword.
oIt
can have abstract and non-abstract methods.
oIt
cannot be instantiated.
oIt
can have constructors and static methods also.
oIt
can have final methods which will force the subclass not to change the body of
the method.
Example of abstract class
1.abstract
class A{}
Abstract Method in Java
A
method which is declared as abstract and does not have implementation is known
as an abstract method.
Example
of abstract method
1.abstract
void printStatus();//no method body and abstract
Example of Abstract class that has an
abstract method
In
this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
Example
of Abstract class that has an abstract method
In
this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
abstract
class Bike
{
abstract
void run();
}
class
Honda4 extends Bike
{
void
run()
{
System.out.println("running
safely");
}
public
static void main(String args[])
{
Bike
obj = new Honda4();
obj.run();
}
}
Compile
by: javac Honda4.java
Run
by: java Honda4
running
safely..
Difference between abstract class and
interface
Abstract
class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between
abstract class and interface that are given below.
Abstract
class Interface
1)Abstract
class can have abstract and non-abstractmethods.Interface can have only
abstract methods. Since Java 8, it can have default and static methods also.
2)Abstract
class doesn't support multiple inheritance.Interface supports multiple
inheritance.
3)Abstract
class can have final, non-final, static and non-static variables.Interface has
only static and final variables.
4)Abstract
class can provide the implementation of interface.Interface can't provide the
implementation of abstract class.
5)The
abstract keyword is used to declare abstract class.The interface keyword is
used to declare interface.
6)An
abstract class can extend another Java class and implement multiple Java
interfaces. An interface can extend
another Java interface only.
7)An
abstract class can be extended using keyword "extends".An interface
can be implemented using keyword "implements".
8)A
Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by
default.
9)Example:
public
abstract class Shape
{
public
abstract void draw();
}
Example:
public
interface Drawable
{
void
draw();
}
Simply,
abstract class achieves partial abstraction (0 to 100%) whereas interface
achieves fully abstraction (100%).
Example of abstract class and interface
in Java
//Creating
interface that has 4 methods
interface
A
{
void
a();//bydefault, public and abstract
void
b();
void
c();
void
d();
}
//Creating
abstract class that provides the implementation of one method of A
interface
abstract
class B implements A
{
public
void c(){System.out.println("I am C");}
}
//Creating
subclass of abstract class, now we need to provide the implementation of rest
of the methods
class
M extends B
{
public
void a(){System.out.println("I am a");}
public
void b(){System.out.println("I am b");}
public
void d(){System.out.println("I am d");}
}
//Creating
a test class that calls the methods of A interface
class
Test5
{
public
static void main(String args[]){
A
a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output:
I am a
I am b
I am c
I am d
Types of polymorphism in java- Runtime
and Compile time polymorphism
types
of polymorphism. There are two types of polymorphism in java:
1)Static
Polymorphism also known as compile time polymorphism
2)Dynamic
Polymorphism also known as runtime polymorphism
Polymorphism
is one of the OOPs feature that allows us to perform a single action in
different ways.
Runtime Polymorphism (or Dynamic
polymorphism)
It
is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in
which a call to an overridden method is resolved at runtime, thats why it is
called runtime polymorphism.
class
ABC
{
public
void myMethod()
{
System.out.println("Overridden
Method");
}
}
public
class XYZ extends ABC
{
public
void myMethod()
{
System.out.println("Overriding
Method");
}
public
static void main(String args[]){
ABC
obj = new XYZ();
obj.myMethod();
}
}
Output:
Overriding
Method
Compile time Polymorphism (or Static
polymorphism)
Polymorphism
that is resolved during compiler time is known as static polymorphism. Method
overloading is an example of compile time polymorphism.
Method Overloading: This allows us
to have more than one method having the same name, if the parameters of methods
are different in number, sequence and data types of parameters
class
SimpleCalculator
{
int
add(int a, int b)
{
return
a+b;
}
int add(int a, int b, int c)
{
return
a+b+c;
}
}
public
class Demo
{
public
static void main(String args[])
{
SimpleCalculator
obj = new SimpleCalculator();
System.out.println(obj.add(10,
20));
System.out.println(obj.add(10,
20, 30));
}
}
Output:
30
60
Method Overloading in Java
If
a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
If
we have to perform only one operation, having same name of the methods
increases the readability of the program.
Advantage of method overloading
Method
overloading increases the readability of the program.
Different
ways to overload the method
There
are two ways to overload the method in java
1.By
changing number of arguments
2.By
changing the data type
Method Overloading: changing no. of
arguments
class
Adder
{
static
int add(int a,int b){return a+b;}
static
int add(int a,int b,int c){return a+b+c;}
}
class
TestOverloading1
{
public
static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
22
33
Method Overloading: changing data type
of arguments
class
Adder
{
static
int add(int a, int b)
{
return
a+b;
}
static
double add(double a, double b)
{
return
a+b;
}
}
class
TestOverloading2
{
public
static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
22
24.9
Method Overriding in Java
If
subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java.
In
other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method
overriding.
Usage of Java Method Overriding
oMethod
overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
oMethod
overriding is used for runtime polymorphism
Rules
for Java Method Overriding
1.The
method must have the same name as in the parent class
2.The
method must have the same parameter as in the parent class.
3.There
must be an IS-A relationship (inheritance).
//Java
Program to demonstrate why we need method overriding
//Here,
we are calling the method of parent class with child
//class
object.
//Creating
a parent class
class
Vehicle
{
void
run()
{
System.out.println("Vehicle
is running");
}
}
//Creating
a child class
class
Bike extends Vehicle
{
public
static void main(String args[]){
//creating
an instance of child class
Bike
obj = new Bike();
//calling
the method with child class instance
obj.run();
}
}
Output:
Vehicle
is running
Can we override static method?
No,
a static method cannot be overridden. It can be proved by runtime polymorphism,
so we will learn it later.
Why can we not override static method?
It
is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs
to the heap area.
Can we override java main method?
No,
because the main is a static method.
Difference between method overloading
and method overriding in java
1)Method
overloading is used to increase the readability of the program.Method
overriding is used to provide the specific implementation of the method that is
already provided by its super class.
2)Method
overloading is performed within class.Method overriding occurs in two classes
that have IS-A (inheritance) relationship.
3)In
case of method overloading, parameter must be different.In case of method
overriding, parameter must be same.
4)Method
overloading is the example of compile time polymorphism.Method overriding is
the example of run time polymorphism.
5)In
java, method overloading can't be performed by changing return type of the
method only. Return type can be same or different in method overloading. But
you must have to change the parameter.Return type must be same or covariant in
method overriding.
Java Method Overloading example
class
OverloadingExample
{
static
int add(int a,int b)
{
return
a+b;
}
static
int add(int a,int b,int c)
{
return
a+b+c;
}
}
Java Method Overriding example
class
Animal
{
void
eat()
{
System.out.println("eating...");
}
}
class
Dog extends Animal
{
void
eat()
{
System.out.println("eating
bread...");
}
}
Java Inner Classes
Java
inner class or nested class is a class which is declared inside the class or
interface.
We
use inner classes to logically group classes and interfaces in one place so
that it can be more readable and maintainable.
Additionally,
it can access all the members of outer class including private data members and
methods.
Syntax
of Inner class
class
Java_Outer_class
{
//code
class
Java_Inner_class
{
//code
}
}
Advantage of java inner classes
There
are basically three advantages of inner classes in java. They are as follows:
1)Nested
classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2)Nested
classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3)Code
Optimization: It requires less code to write.
Difference between nested class and
inner class in Java
Inner
class is a part of nested class. Non-static nested classes are known as inner
classes.
Types of Nested classes
There
are two types of nested classes non-static and static nested classes.The
non-static nested classes are also known as inner classes.
oNon-static nested class (inner class)
1.Member
inner class
2.Anonymous
inner class
3.Local
inner class
oStatic nested class
Member
Inner Class:-A class created within class and outside method.
Anonymous
Inner Class:-A class created for implementing interface or extending class. Its
name is decided by the java compiler.
Local
Inner Class:-A class created within method.
Static
Nested Class:-A static class created within class.
Nested
Interface:-An interface created within class or interface
Inner class
An
inner class is declared inside the curly braces of another enclosing class.
Inner class is coded inside a Top level class as shown below:-
//Top
level class definition
class
MyOuterClassDemo
{
private
int myVar= 1;
//
inner class definition
class
MyInnerClassDemo
{
public
void seeOuter ()
{
System.out.println("Value
of myVar is :" + myVar);
}
}
// close inner class definition
}
// close Top level class definition
Anonymous Inner Classes
It
is a type of inner class which
1.has
no name
2.can
be instantiated only once
3.is
usually declared inside a method or a code block ,a curly braces ending with
semicolon.
4.is
accessible only at the point where it is defined.
5.does
not have a constructor simply because it does not have a name
6.cannot
be static
Example:
package
beginnersbook.com;
class
Pizza
{
public
void eat()
{
System.out.println("pizza");
}
}
class
Food
{
/*
There is no semicolon(;)
*
semicolon is present at the curly braces of the method end.
*/
Pizza
p = new Pizza()
{
public
void eat()
{
System.out.println("anonymous
pizza");
}
};
}
Access Modifiers in Java
There
are two types of modifiers in Java: access modifiers and non-access modifiers.
The
access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.
There
are four types of Java access modifiers:
1.Private:
The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2.Default:
The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it
will be the default.
3.Protected:
The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4.Public:
The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the
package.
Examples of Private
class
A
{
private
int data=40;
private
void msg()
{
System.out.println("Hello
java");
}
}
public
class Simple
{
public
static void main(String args[])
{
A
obj=new A();
System.out.println(obj.data);//Compile
Time Error
obj.msg();//Compile
Time Error
}
}
Default
//save
by A.java
package
pack;
class
A
{
void
msg(){System.out.println("Hello");}
}
//save
by B.java
package
mypack;
import
pack.*;
class
B
{
public
static void main(String args[]){
A
obj = new A();//Compile Time Error
obj.msg();//Compile
Time Error
}
}
Protected
//save
by A.java
package
pack;
public
class A{
protected
void msg(){System.out.println("Hello");}
}
//save
by B.java
package
mypack;
import
pack.*;
class
B extends A
{
public
static void main(String args[]){
B
obj = new B();
obj.msg();
}
}
Public
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String
args[])
{
A obj = new A();
obj.msg();
}
}
non-access
modifiers
•The static modifier for creating
class methods and variables.
•The final modifier for
finalizing the implementations of classes, methods, and variables.
•The abstract modifier for
creating abstract classes and methods.
•The synchronized and volatile
modifiers, which are used for threads.
Final
Keyword In Java
The final keyword in java is used
to restrict the user. The java final keyword can be used in many context. Final
can be:
1.variable
2.method
3.class
The final keyword can be applied
with the variables, 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. We will have detailed learning of these. Let's first
learn the basics of final keyword.
Java
final variable
If you make any variable as
final, you cannot change the value of final variable(It will be constant).
class Bike9
{
final int speedlimit=90;//final
variable
void run()
{
speedlimit=400;
}
public static void main(String
args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error
Example
of final method
class Bike
{
final void
run(){System.out.println("running");}
}
class Honda extends Bike
{
void run()
{
System.out.println("running
safely with 100kmph");
}
public static void main(String
args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
Example
of final class
final class Bike{}
class Honda1 extends Bike
{
void
run(){System.out.println("running safely with 100kmph");}
public static void main(String
args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error
Is
final method inherited?
Ans) Yes, final method is
inherited but you cannot override it. For Example:
class Bike
{
inal void
run(){System.out.println("running...");}
}
class Honda2 extends Bike
{
public static void main(String
args[]){
new Honda2().run();
}
}
Java
static keyword
The static keyword in Java is
used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the
class than an instance of the class.
The static can be:
1.Variable (also known as a class
variable)
2.Method (also known as a class
method)
//Java Program to demonstrate the
use of a static method.
class Student
{
int rollno;
String name;
static String college =
"ITS";
//static method to change the
value of static variable
static void change()
{
college = "BBDIT";
}
//constructor to initialize the
variable
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+"
"+name+" "+college);
}
}
//Test class to create and
display the values of object
public class TestStaticMethod
{
public static void main(String
args[]){
Student.change();//calling change
method
//creating objects
Student s1 = new
Student(111,"Karan");
Student s2 = new
Student(222,"Aryan");
Student s3 = new
Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Java
Package
A java package is a group of
similar types of classes, interfaces and sub-packages.
Package in java can be
categorized in two form, built-in package and user-defined package.
There are many built-in packages
such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage
of Java Package
1)Java package is used to
categorize the classes and interfaces so that they can be easily maintained.
2)Java package provides access
protection.
3)Java package removes naming
collision.
Types
of packages in Java
As mentioned in the beginning of
this guide that we have two types of packages in java.
1 User defined package: The
package we create is called user-defined package.
2)Built-in package: The already
defined package like java.io.*, java.lang.* etc are known as built-in packages.
Wrapper
classes in Java
The wrapper class in Java
provides the mechanism to convert primitive into object and object into
primitive.
Since J2SE 5.0, autoboxing and
unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Use
of Wrapper classes in Java
Java is an object-oriented
programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different
scenarios, where we need to use the wrapper classes.
oChange the value in Method: Java
supports only call by value. So, if we pass a primitive value, it will not
change the original value. But, if we convert the primitive value in an object,
it will change the original value.
oSerialization: We need to
convert the objects into streams to perform the serialization. If we have a
primitive value, we can convert it in objects through the wrapper classes.
oSynchronization: Java
synchronization works with objects in Multithreading.
ojava.util package: The java.util
package provides the utility classes to deal with objects.
oCollection Framework: Java
collection framework works with objects only. All classes of the collection
framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang
package are known as wrapper classes in Java. The list of eight wrapper classes
are given below:
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Wrapper class Example: Primitive
to Wrapper
//Java program to convert
primitive into objects
//Autoboxing example of int to
Integer
public class WrapperExample1
{
public static void main(String
args[])
{
//Converting int into
Integer
int a=20;
Integer i=Integer.valueOf(a);//converting
int into Integer explicitly
Integer j=a;//autoboxing, now
compiler will write Integer.valueOf(a) internally
System.out.println(a+"
"+i+" "+j);
}
}
Output:
20 20 20