JAVA
Java is an Object-Oriented Language. As a
language that has the Object-Oriented feature, Java supports the following
fundamental concepts
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Objects
in Java
An entity that has state and behavior is
known as an object e.g. chair, bike, marker, pen, table, car etc. It can be
physical or logical
An object has three characteristics:
state: represents
data (value) of an object.
behavior: represents
the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object
identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.
Class
in Java
Class − A class can be
defined as a template/blueprint that describes the behavior/state that
the object of its type support.
Syntax to declare a class:
class <class_name>{
}
A class in Java can contain:
Variables
Methods
Constructors
Blocks
Variables:
Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a
combination of "vary + able" that means its value can be changed
data_type variable_name = value;
A class can contain any of the following variable types.
Local variables − Variables defined inside methods,
constructors or blocks are called local variables. The variable will be
declared and initialized within the method and the variable will be destroyed
when the method has completed.
Instance variables − Instance variables are
variables within a class but outside any method. These variables are
initialized when the class is instantiated. Instance variables can be accessed
from inside any method, constructor or blocks of that particular class.
Class/static variables − Class variables are
variables declared within a class, outside any method, with the static keyword.
Method in Java
In java, a method is like function i.e. used to expose
behavior of an object.It is a collection of
statements that are grouped together to perform an operation.
Syntax:
modifier returnType nameOfMethod
(Parameter List) {
}
The syntax shown above includes −
modifier − It defines the access type of the method and
it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature
consists of the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order,
and number of parameters of a method. These are optional, method may contain
zero parameters.
method body − The method body defines what the method does
with the statements.
A class can contain any of the following methods
Instance Method
Instance method are methods which require an object of its
class to be created before it can be called. To invoke a instance method, we
have to create an Object of the class in within which it defined.
public class InstanceMethod {
public void HahaSkills(String name)
{
//Code to be excuted
}
//Return type can be int,float,String
or user defind data type
}
Memory allocation: These
methods themselves are stored in Permanent Generation space of heap but the
parameters (arguments passed to them) and their local variables and the value
to be returned are allocated in stack. They can be called within the same class
in which they reside or from the different classes defined either in the same
package or other packages depend on the access type provided
to the desired instance method
Static Method
Static methods are the methods in Java that can be called
without creating an object of class. They are referenced by the class name itself or reference to the Object of that
class.
public class StaticMethod {
public static void HahaSkills(String name)
{
//Code to be excuted
}
//Return type can be int,float,String
or user defind data type
}
Memory Allocation: They are
stored in Permanent Generation space of heap as they are associated to the class
in which they reside not to the objects of that class. But their local
variables and the passed argument(s) to them are stored in the stack. Since
they belong to the class so they can be called to without creating the object
of the class.
Constructors
A constructor initializes an object when it is created. It
has the same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values
to the instance variables defined by the class, or to perform any other startup
procedures required to create a fully formed object.
All classes have constructors, whether you define one or
not, because Java automatically provides a default constructor that initializes
all member variables to zero. However, once you define your own constructor,
the default constructor is no longer used.
Here is a simple example that uses a constructor without
parameters −
// A simple constructor.
public class defconstructor {
int id;
String name;
void
defconstructur(){System.out.println(id+" "+name);}
public static void main(String args[]){
defconstructor
s1=new defconstructor();
defconstructor
s2=new defconstructor();
}
}
OUTPUT
0 null
0 null
Blocks
Two types of blocks instance block and
static block.
Static
block: Static blocks are
loaded first while the program is loaded and it doesnot depend upon the
instances of the class.
Instance block: Instance blocks are dependent
upon the instances of the class it is called each time one instance is created
block. Initialization blocks run when the class is first loaded (a static
initialization block) or when an instance is created (an instance initialization
block). Let's look at an example
public class Block{
int x=10;
{System.out.println("normal
block");}
static{System.out.println("static
block");}
public static void main(String[] args){
Block d=new Block();
Block d1=new Block();
System.out.println(d.x);
}
}
Output:
static block
normal block
normal block
10
Inheritance
Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
The idea behind inheritance in java is that you can create
new classes that are built upon existing classes. When you inherit from an
existing class, you can reuse methods and fields of parent class, and you can
add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in
java
For Method Overriding (so
runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
The extend class Subclass-name
extends Superclass-name
{
}
s keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to
increase the functionality.
In the terminology of Java, a class which is inherited is
called parent or super class and the new class is called child or subclass.
Types of inheritance in Java:
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends
another one class only then we call it a single inheritance. The below
flow diagram shows that class B extends only one class which is A. Here A is
a parent class of B and B would
be a child class of
A.
public class Animal {
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
span>d.bark();
d.eat();
}
}
OUTPUT:
eating...
barking...
2) Multiple Inheritance
"Multiple Inheritance"
refers to the concept of one class extending (Or inherits) more than one base
class. The inheritance we learnt earlier had the concept of one base class or
parent. The problem with "multiple inheritance"is that the derived
class will have to manage the dependency on two base classes.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it
were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg()
method would be invoked?
}
}
OUTPUT:
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can
inherit from a derived class, thereby making this derived class the base class
for the new class. As you can see in below flow diagram C is subclass or child
class of B and B is a child class of A.
Class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
OUTPUT:
eating...
barking...
weeping...
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}
OUTPUT:
meowing...
eating...
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a
combination of Single and Multiple inheritance. A typical flow diagram
would look like below. A hybrid inheritance can be achieved in the java in a
same way as multiple inheritance can be!! Using interfaces. yes you
heard it right. By using interfaces you
can have multiple as well as hybrid inheritance in
Java.
Polymorphism in Java
The process of representing one form in multiple forms is
known as Polymorphism.
Polymorphism is derived from 2 greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism
means many forms.
Polymorphism is not a programming concept but it is one of
the principal of OOPs. For many objects oriented programming language
polymorphism principle is common but whose implementations are varying from one
objects oriented programming language to another object oriented programming
language.
There are two types of polymorphism in java:
Static
Polymorphism (also
known as compile time polymorphism)
Dynamic Polymorphism( also known as runtime polymorphism)
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
{
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:
60
Runtime Polymorphism (or
Dynamic polymorphism)
Dynamic polymorphism is a process in which
a call to an overridden method is resolved at runtime, thats why it is called
runtime polymorphism. Method overriding is
an example of compile time polymorphism.
Method Overriding: Declaring a method in sub class which is already present in parent class is known as method overriding.
Overriding is done so that a child class can give its own implementation to a
method which is already provided by the parent class. In this case the method in
parent class is called overridden method and the method in child class is
called overriding method.
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run();
}
}
OUTPUT:
Encapsulation
The whole idea behind encapsulation is to hide the
implementation details from users. If a data member is private it means it can
only be accessed within the same class. No outside class can access private
data member (variable) of other class. This way
data can only be accessed by public methods thus making the private fields and
their implementation hidden for outside classes.
How to implement encapsulation in java:
1) Make the instance variables private so that
they cannot be accessed directly from outside the class. You can only set and
get values of these variables through the methods of the class.
2) Have getter and setter methods in the class
to set and get the values of the fields
Advantages of
encapsulation
It improves maintainability and flexibility and re-usability
.The implementation is purely hidden for outside class. This improves the
re-usability of the underlying class.
For e.g. If we have a field(or variable) that we want to be changed so we simply define the
variable as private and instead of set and get both we just need to define the
get method for that variable. Since the set method is not present there is no
way an outside class can modify the value of that field.
User would not be knowing what is going on behind the scene.
They would only be knowing that to update a field call set method and to read a
field call get method but what these set and get methods are doing is purely
hidden from them.
Abstraction in Java
Abstraction is
the concept of exposing only the required essential characteristics and
behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming language
this is implemented automatically while writing the code in the form of class
and object.
In Java, abstraction is achieved using
Abstract classes and interfaces.
Abstract
Class
A class which contains the abstract keyword in its
declaration is known as abstract class.
Abstract classes may or may not contain abstract methods, i.e., methods
without body ( public void get(); )
But, if a class has at least one abstract method, then the
class mustbe declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from
another class, provide implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
abstract class Base {
abstract void fun();
}
class Derived extends Base {
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
// Uncommenting
the following line will cause compiler error as the
// line
tries to create an instance of abstract class.
//
Base b = new Base();
// We
can have references of Base type.
Base b = new Derived();
b.fun();
}
}
OUTPUT
Derived fun()called
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.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are
given below.
It is used to achieve
abstraction.
By interface, we can
support the functionality of multiple inheritance.
It can be used to achieve
loose coupling.
interface printable{
void print();
}
class interface1 implements printable{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
interface1 obj = new interface1();
obj.print();
}
}
OUTPUT:
Hello