Classes Objects Methods Constructors in Java
Classes Objects Methods Constructors in Java
Object is the physical as well as logical entity where as class is the only logical entity.
Class: Class is a blue print which is containing only list of variables and method and no memory is
allocated for them. A class is a group of objects that has common properties.
Data Member
Method
Constructor
Block
Class and Interface
State
Behavior
Identity
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.
In real world many examples of object and class like dog, cat, and cow are belong to animal's class.
Each object has state and behaviors. For example a dog has state:- color, name, height, age as well as
behaviors:- barking, eating, and sleeping.
https://canvas.instructure.com/courses/1480238/pages/classes-objects-methods-constructors-this-keyword?module_item_id=21012846 1/19
Vehicle class
Car, bike, truck these all are belongs to vehicle class. These Objects have also different different states
and behaviors. For Example car has state - color, name, model, speed, Mileage. as we;; as behaviors -
distance travel
Class Object
Class is a container which
1 collection of variables and object is a instance of class
methods.
2 No memory is allocated at the Sufficient memory space will be allocated for all the
time of declaration variables of class at the time of declaration.
One class definition should exist
3 For one class multiple objects can be created.
only once in the program.
class Class_Name
{
data member; method;
}
In this example, we have created a Employee class that have two data members eid and ename. We are
creating the object of the Employee class by new keyword and printing the objects value.
Example
r instance variable) String ename;// data member (or instance variable) eid=101;
tring args[])
Output
Note: A new keyword is used to allocate memory at runtime, new keyword is used for create an object of
class, later we discuss all the way for create an object of class.
Access Modifiers in Java
Access modifiers are those which are applied before data members or methods of a class. These are
used to where to access and where not to access the data members or methods. In Java programming
these are classified into four types:
Private
Default (not a keyword)
Protected
Public
Note: Default is not a keyword (like public, private, protected are keyword)
If we are not using private, protected and public keywords, then JVM is by default taking as default
access modifiers.
private: Private members of class in not accessible anywhere in program these are only accessible
within the class. Private are also called class level access modifiers.
Example
Hello
.out.println("Hello java");
class Demo
obj=new Hello();
.out.println(obj.a); //Compile Time Error, you can't access private data obj.show();//Compile Time Error, you can't access private m
public: Public members of any class are accessible anywhere in the program in the same class and
outside of class, within the same package and outside of the package. Public are also called universal
access modifiers.
Example
class Hello
{
public int a=20; public void show()
{
System.out.println("Hello java");
}
}
Output
20
Hello Java
protected: Protected members of the class are accessible within the same class and another class of
the same package and also accessible in inherited class of another package. Protected are also called
derived level access modifiers.
In below the example we have created two packages pack1 and pack2. In pack1, class A is public so we
can access this class outside of pack1 but method show is declared as a protected so it is only
accessible outside of package pack1 only through inheritance.
Example
// save A.java package pack1; public class A
{
protected void show()
{
System.out.println("Hello Java");
}
}
class B extends A
{
public static void main(String args[]){ B obj = new B();
obj.show();
}
}
Output
Hello Java
default: Default members of the class are accessible only within the same class and another class of the
same package. The default are also called package level access modifiers.
Example
//save by A.java package pack; class A
{
void show()
{
System.out.println("Hello Java");
}
}
bj = new A(); //Compile Time Error, can't access outside the package obj.show();//Compile Time Error, can't access outside the pack
Output
Hello Java
Note: private access modifier is also known as native access modifier, default access modifier is also
known as package access modifier, protected access modifier is also known as an inherited access
modifier, public access modifier is also known as universal access modifier.
Constructor in Java
constructor in Java is a special member method which will be called implicitly (automatically) by the
JVM whenever an object is created for placing user or programmer defined values in place of default
values. In a single word constructor is a special member method which will be called automatically
whenever object is created.
The purpose of constructor is to initialize an object called object initialization. Constructors are mainly
create for initializing the object. Initialization is a process of assigning user defined values at the time of
allocation of memory space.
Syntax
className()
{
.......
.......
}
Output
Sum: 30
In above example when we create an object of "Sum" class then constructor of this class call and
initialize user defined value in a=10 and b=20. if we can not create constructor of Sum class then it print "
Sum: 0 " because default values of integer is zero.
Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters.
If any class does not contain at least one user defined constructor than the system will create a default
constructor at the time of compilation it is known as system defined default constructor.
Note: System defined default constructor is created by java compiler and does not have any statement in
the body part. This constructor will be executed every time whenever an object is created if that class
does not contain any user defined constructor.
In below example, we are creating the no argument constructor in the Test class. It will be invoked at the
time of object creation.
Example
//TestDemo.java class Test
{
int a, b; Test ()
{
System.out.println("I am from default Constructor..."); a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
};
class TestDemo
{
public static void main(String [] args)
{
Test t1=new Test ();
}
};
Output
Output:
I am from default Constructor... Value of a: 10
Value of b: 20
Rule-1:
Whenever we create an object only with default constructor, defining the default constructor is optional. If
we are not defining default constructor of a class, then JVM will call automatically system defined default
constructor. If we define, JVM will call user defined default constructor.
Output
Roll: 0
Marks: 0.0 Name: null
Explanation: In the above class, we are not creating any constructor so compiler provides a default
constructor. Here 0, 0.0 and null values are provided by default constructor.
parameterized constructor
If any constructor contain list of variable in its signature is known as paremetrized constructor. A
parameterized constructor is one which takes some parameters.
Syntax
class ClassName
{
.......
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
Example
class Test
{
int a, b; Test ()
{
System.out.println("I am from default Constructor..."); a=1;
b=2;
System.out.println("Value of a ="+a); System.out.println("Value of b ="+b);
}
Test (int x, int y)
{
System.out.println("I am from double Paraceterized Constructor"); a=x;
b=y;
System.out.println("Value of a ="+a); System.out.println("Value of b ="+b);
}
Test (int x)
{
System.out.println("I am from single Parameterized Constructor"); a=x;
b=x;
System.out.println("Value of a ="+a); System.out.println("Value of b ="+b);
}
Test (Test T)
{
System.out.println("I am from Object Parameterized Constructor..."); a=T.a;
b=T.b;
System.out.println("Value of a ="+a); System.out.println("Value of b ="+b);
}
};
class TestDemo2
{
public static void main (String k [])
{
Test t1=new Test ();
Test t2=new Test (10, 20); Test t3=new Test (1000); Test t4=new Test (t1);
}
};
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists.The compiler differentiates these constructors by taking the number of
parameters, and their type.
In other words whenever same constructor is existing multiple times in the same class with different
number of parameters or order of parameters or type of parameters is known as Constructor
overloading.
In general constructor overloading can be used to initialized same or different objects with different
values.
Syntax
class ClassName
{
ClassName()
{
..........
..........
}
ClassName(datatype1 value1)
{.......}
ClassName(datatype1 value1, datatype2 value2)
{.......}
ClassName(datatype2 variable2)
{.......}
ClassName(datatype2 value2, datatype1 value1)
{.......}
........
}
The scope of constructor is within the class so that it is not possible to achieved overriding at constructor
level.
At the time of class loading if we want to perform any activity we have to define that activity inside static
block because this block execute at the time of class loading.
In a class we can take any number of static block but all these blocks will be execute from top to bottom.
Syntax
static
{
........
//Set of Statements
........
}
Note: In real time application static block can be used whenever we want to execute any instructions or
statements before execution of main method.
Output
Hello how are u ? This is main()
Output
Output:
Hello how are u ?
Exception is thread "main" java.lang.no-suchmethodError:Main
Note: "Exception is thread "main" java.lang.no-suchmethodError:Main" warning is given in java 1.7 and
its above versions
Output
Output:
First static block Second static block This is main()
Note: "Here static block run according to there order (sequence by) from top to bottom.
A class has to be loaded in main memory before we start using it. Static block is executed during class
loading. This is the reason why a static block executes before the main method.
Memory is allocated for these variable Memory is allocated for these variable at the
2
whenever an object is created time of loading of the class.
3 Memory is allocated multiple time Memory is allocated for these variable only
whenever a new object is created. once in the program.
Non-static variable also known as
Memory is allocated at the time of loading of
instance variable while because
4 class so that these are also known as class
memory is allocated whenever instance
variable.
is created.
Static variable are common for every object
Non-static variable are specific to an that means there memory location can be
5
object sharable by every object reference or same
class.
Non-static variable can access with
Static variable can access with class reference.
object reference.
Syntax Syntax
6
class_name.variable_name
obj_ref.variable_name
Note: static variable not only can be access with class reference but also some time it can be accessed
with object reference.
Memory is allocated multiple time whenever Memory is allocated only once at the time of class
2
method is calling. loading.
It is specific to an object so that these are also These are common to every object so that it is also
3
known as instance method. known as member method or class method.
4 These methods always access with object These property always access with class reference
reference Syntax:
Syntax:
className.methodname();
Objref.methodname();
If any method wants to be execute multiple If any method wants to be execute only once in the
5
time that can be declare as non static. program that can be declare as static .
Note: In some cases static methods not only can access with class reference but also can access with
object reference.