0% found this document useful (0 votes)
147 views19 pages

Classes Objects Methods Constructors in Java

1) Classes, objects, methods, and constructors are key concepts in object-oriented programming in Java. A class defines the attributes and behaviors of an object, while an object is an instance of a class. 2) A constructor is a special method that initializes an object and is called automatically when an object is created. Constructors eliminate the need for default values by allowing the programmer to define initialization values. 3) The document provides examples to illustrate the differences between classes and objects, and demonstrates how a constructor can be used to initialize object attributes when an object is created.

Uploaded by

Akhdan Mumtaz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
147 views19 pages

Classes Objects Methods Constructors in Java

1) Classes, objects, methods, and constructors are key concepts in object-oriented programming in Java. A class defines the attributes and behaviors of an object, while an object is an instance of a class. 2) A constructor is a special method that initializes an object and is called automatically when an object is created. Constructors eliminate the need for default values by allowing the programmer to define initialization values. 3) The document provides examples to illustrate the differences between classes and objects, and demonstrates how a constructor can be used to initialize object attributes when an object is created.

Uploaded by

Akhdan Mumtaz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

3/30/2019 Classes, Objects, Methods, Constructors, this keyword: Your Guided Course Template

Classes, Objects, Methods,


Constructors, this keyword
Object and class 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.

A class in java contains:

Data Member
Method
Constructor
Block
Class and Interface

Object: Object is a instance of class, object has state and behaviors.

An Object in java has three characteristics:

State
Behavior
Identity

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 is also can be used to achieve user defined data types.

Real life example of object and class

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

Difference between Class and Object in Java

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.

Syntax to declare a Class

class Class_Name
{
data member; method;
}

Simple Example of Object and Class

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[])

; // Creating an object of class Employee System.out.println("Employee ID: "+e.eid); System.out.p

Output

Employee ID: 101 Name: Hitesh

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

e int a=20; private void show()

.out.println("Hello java");

class Demo

static void main(String args[])

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");
}
}

public class Demo


{
public static void main(String args[])
{
Hello obj=new Hello(); System.out.println(obj.a); obj.show();
}
}

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");
}
}

//save B.java package pack2;


import pack1.*;

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");
}
}

ave by B.java package pack2; import pack1.*; class B

lic static void main(String args[])

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.

Rules for access modifiers:


The following diagram gives rules for Access modifiers.

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()
{
.......
.......
}

Advantages of constructors in Java

A constructor eliminates placing the default values.


A constructor eliminates calling the normal or ordinary method implicitly.

How Constructor eliminate default values ?


Constructor are mainly used for eliminate default values by user defined values, whenever we create an
object of any class then its allocate memory for all the data members and initialize there default values.
To eliminate these default values by user defined values we use constructor.

Constructor Example in Java


class Sum
{
int a,b; Sum()
{ a=10; b=20;
}
public static void main(String s[])
{
Sum s=new Sum(); c=a+b;
System.out.println("Sum: "+c);
}
}

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.

Rules or properfies of a constructor


Constructor will be called automatically when the object is created.
Constructor name must be similar to name of the class.
Constructor should not return any value even void also. Because basic aim is to place the value in
the object. (if we write the return type for the constructor then that constructor will be treated as
ordinary method).
Constructor definitions should not be static. Because constructors will be called each and every time,
whenever an object is creating.
Constructor should not be private provided an object of one class is created in another class
(Constructor can be private provided an object of one class created in the same class).
Constructors will not be inherited from one class to another class (Because every class constructor is
create for initializing its own data members).
The access specifier of the constructor may or may not be private.
1. If the access specifier of the constructor is private then an object of corresponding class can be
created in the context of the same class but not in the context of some other classes.
2. If the access specifier of the constructor is not private then an object of corresponding class can be
created both in the same class context and in other class context.

Difference between Method and Constructor


Method Constructor
1 Method can be any user defined name Constructor must be class name
It should not have any return type (even
2 Method should have return type
void)
Method should be called explicitly either It will be called automatically whenever
3
with object reference or class reference object is created
The java compiler provides a default
Method is not provided by compiler in any
4 constructor if we do not have any
case.
constructor.
Types of constructors
Based on creating objects in Java constructor are classified in two types. They are

Default or no argument Constructor


Parameterized constructor.

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.

Syntax of Default Constructor


class className
{
.....// Call default constructor clsname ()
{
Block of statements; // Initialization
}
.....
}

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.

Example of default 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.

Purpose of default constructor?


Default constructor provides the default values to the object like 0, 0.0, null etc. depending on their type
(for integer 0, for string null).

Example of default constructor that displays the


default values
class Student
{
int roll; float marks; String name; void show()
{
System.out.println("Roll: "+roll); System.out.println("Marks: "+marks); System.out.println("Name: "+name);
}
}
class TestDemo
{
public static void main(String [] args)
{
Student s1=new Student(); s1.show();
}
}

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
{
.......
}
.......
}

Syntax to call parametrized constructor


ClassName objref=new ClassName(value1, value2,.);
OR
new ClassName(value1, value2,.);

Example of Parametrized Constructor


class Test
{
int a, b;
Test(int n1, int n2)
{
System.out.println("I am from Parameterized Constructor..."); a=n1;
b=n2;
System.out.println("Value of a = "+a); System.out.println("Value of b = "+b);
}
};
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20);
}
};

Important points Related to Parameterized Constructor


Whenever we create an object using parameterized constructor, it must be define parameterized
constructor otherwise we will get compile time error. Whenever we define the objects with respect to
both parameterized constructor and default constructor, It must be define both the constructors.
In any class maximum one default constructor but 'n' number of parameterized constructors.

Example of default constructor, parameterized constructor


and overloaded 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);
}
};

Note By default the parameter passing mechanism is call by reference.

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)
{.......}
........
}

Why overriding is not possible at constructor level.

The scope of constructor is within the class so that it is not possible to achieved overriding at constructor
level.

Stafic Block in Java


Static block is a set of statements, which will be executed by the JVM before execution of main method.

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.

Example of Stafic Block


class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}

Output
Hello how are u ? This is main()

Run java program without main method


class StaticDemo
{
static
{
System.out.println("Hello how are u ?");
}
}

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

More than one stafic block in a program


class StaticDemo
{
static
{
System.out.println("First static block");
}
static
{
System.out.println("Second Static block");
}
public static void main(String args[])
{
System.out.println("This is main()");
}
}

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.

Why a stafic block executes before the main method ?

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.

Difference between non-stafic and stafic variable


Non-static variable Static variable
These variables are preceded by static
These variable should not be preceded keyword.
by any static keyword Example:
Example
class A
1 {
class A
int a;
{
}
static int b;
}

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.

Difference between non-stafic and stafic Method


Non-Static method Static method
These method never be preceded by static
These method always preceded by static keyword
keyword
Example:
Example:
static void fun2()
void fun1() {
1 { ......
...... ......
...... }
}

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.

You might also like