0% found this document useful (0 votes)
5 views51 pages

Java Classes and Objects Overview

The document provides an overview of classes and objects in Java programming, explaining key concepts such as class declaration, object creation, instance variables, methods, constructors, and garbage collection. It includes syntax examples and explanations of static variables and methods, as well as the use of the 'this' keyword. Additionally, it covers constructor overloading and the importance of memory management in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views51 pages

Java Classes and Objects Overview

The document provides an overview of classes and objects in Java programming, explaining key concepts such as class declaration, object creation, instance variables, methods, constructors, and garbage collection. It includes syntax examples and explanations of static variables and methods, as well as the use of the 'this' keyword. Additionally, it covers constructor overloading and the importance of memory management in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RAGHU

ENGINEERING COLLEGE
(AUTONOMOUS | VISAKHAPATNAM)

Unit-II
Classes and Objects

Java Programming RAGHU ENGINEERING COLLEGE 1


Class
• A class can be defined as a template or blueprint that
describes the behavior or state of the object of its type.

• Class is a model for creating objects. This means the


properties and actions of the object are written in the class.
Properties are represented by variables and actions are
represented by methods.

• Class contains variables and methods. The same variables


and methods are also available in the objects, because
objects are created from the class.

Java Programming RAGHU ENGINEERING COLLEGE 2


Class Declaration: Syntax
class class_name
{
datatype variable1;
datatype variable2; // properties or
: // variables
:
return_datatype method_name( ) //action
//or method
{
//statements;
}
}

Java Programming RAGHU ENGINEERING COLLEGE 3


Class: Example
class CSE
{
int year;
int strength;
void display()
{
[Link](“Year:”+year);
[Link](“Strength:”+strength);
}
}

Java Programming RAGHU ENGINEERING COLLEGE 4


Object
• Object is an instance of class.

• To use a class, we should create an object of the class.


Object creation represents allotting necessary memory to
store actual data of the variables.
Syntax:
class_name object_name=new class_name();
Here, new is a keyword that creates an object to the given
class.

• Actually object is a variable of type ‘class’. So, we can treat


class as a datatype and every object is having reference
number, we can get it by using the hashcode() method.
Java Programming RAGHU ENGINEERING COLLEGE 5
Creating Objects: Example
class CSE
{
int year;
void display()
{
[Link]("Welcome to CSE");
}
}
class CSEMain
{
public static void main(String args[])
{
CSE c1=new CSE();
Output:
[Link]();
} Welcome to CSE
}Java Programming RAGHU ENGINEERING COLLEGE 6
Instance Variables
Instance variable in java is used by Objects to store
their states. Variables which are defined without the STATIC
keyword and are Outside any method declaration are Object
specific and are known as instance variables.

They are called so because their values


are instance specific and are not shared among instances.

First way to initialize the instance variables :


First way is to initialize the instance variables of class
in other class by the use of member operator.

Syntax: object_name.variable_name=value;
Java Programming RAGHU ENGINEERING COLLEGE 7
Instance Variables: Example
class CSE
{
int year;
int strength;
void display()
{
[Link]("Year:"+year);
[Link]("Strength:"+strength);
}
}
class CSEMain
{
public static void main(String args[])
{ Output:
CSE c1=new CSE(); Year:2
[Link]=2;
[Link]=128;
Strength:128
[Link]();
}
Java Programming RAGHU ENGINEERING COLLEGE 8
}
Instance Variables

Second way to initialize the instance variables :

The second way of initializing the instance variables is


to initialize them at the time of declaration.

The problem with this way is all the objects are


initialized with same data.

Java Programming RAGHU ENGINEERING COLLEGE 9


Instance Variables: Example
class CSE
{ Output:
int year=2;
Year:2
int strength=128;
void display() Strength:128
{
[Link](“Year:”+year);
[Link](“Strength:”+strength);
}
}
class CSEMain
{
public static void main(String args[])
{
CSE c1=new CSE();
[Link]();
}
} Java Programming RAGHU ENGINEERING COLLEGE 10
Methods
A method is a group of statements that performs a task. Here,
‘task’ represents a calculation or processing of data.
A method has two parts. They are:
• Method header or prototype
• Method body.

Method header or prototype:


Method header contains method name, method
parameters and method return data type. Method header is
written in the form as below:

return_data_type method_name(parameter1,parameter2,…)

Java Programming RAGHU ENGINEERING COLLEGE 11


Methods
• Method parameters are useful to receive data from outside
into the method.

• The ‘return_data_type’ written before the method name is


to represent what type of result or data the method is
returning.

Method body:
Method body consists of a group of statements which
contains logic to perform the task. Below to the method
header, we should write the method body.

Java Programming RAGHU ENGINEERING COLLEGE 12


Methods

Method body can be written in the following format:


{
statements of the method
}

If a method returns some value, then a return statement


should be written within the body of the method as below:
{
statements of the method
return value or variable or expression;
}
Java Programming RAGHU ENGINEERING COLLEGE 13
Methods
Some Examples of return:
return x; //value of x is returned
return 5; //5 is returned
return (x+y); //result of x+y is returned
return -1; //-1 is returned
return object; //object is returned
return arr; //array arr is returned

Calling a method:
We can call the method by using the object name with
the help of member operator as below:
object_name.method_name();
Java Programming RAGHU ENGINEERING COLLEGE 14
Method: Example
class Sample
{ Output:
int sum(int num1,int num2) Sum is:100
{
int res=num1+num2;
return res;
}
}
class MethodDemo
{
public static void main(String args[])
{
Sample s=new Sample();
int result=[Link](70,30);
[Link]("Sum is:"+result);
}
Java Programming RAGHU ENGINEERING COLLEGE 15
}
Constructors
Constructor is similar to a method that is used to initialize the
instance variables of a class. The third possibility of
initializing instance variable is usage of constructor.

Characteristics of Constructor:
• The constructor’s name is same as class name and should
end with a pair of simple braces i.e. ()

• A constructor may or may not have parameters.

• If a constructor does not have any parameters then that is


called as ‘Default constructor’ and if a constructor has one or
more parameters, it is called as ‘Parameterized constructor’.
Java Programming RAGHU ENGINEERING COLLEGE 16
Constructors

•A constructor does not return any value, not even void.

• A constructor is automatically called whenever the object is


created. While creating an object, if nothing is passed to the
object then the default constructor is called and executed. If
some values are passed to the objects, then the parameterized
constructor is called.

• A constructor is called and executed only once per object


creation.

Java Programming RAGHU ENGINEERING COLLEGE 17


Constructor: Example
class CSE
{
int year;
int strength;
void display()
{
[Link]("Year:"+year);
[Link]("Strength:"+strength);
}
CSE()
{
year=2;
strength=128;
[Link]("From default constructor");
} //program continued in next slide
Java Programming RAGHU ENGINEERING COLLEGE 18
Constructor: Example
CSE(int yr,int st)
{
year=yr;
strength=st;
[Link]("From parameterized constructor");
}
} Output:
class CSEMain From default constructor
{ Year:2
public static void main(String args[]) Strength:128
{ From parameterized constructor
CSE c1=new CSE(); Year:3
[Link](); Strength:176
CSE c2=new CSE(3,176);
[Link]();
}
Java Programming RAGHU ENGINEERING COLLEGE 19
}
Constructor Overloading

•Writing two or more constructors with the same name but


with difference in the parameters is called ‘Constructor
Overloading’.

• Such constructors are used to perform different tasks with


the same name.

Java Programming RAGHU ENGINEERING COLLEGE 20


Constructor Overloading: Example
class Add
{
Add()
{
[Link]("Addition from first constructor");
}
Add(int p)
{
[Link]("Value of p:"+p+" from second constructor");
}
Add(int a,int b)
{
int c=a+b;
[Link]("Value of c:"+c+" from third constructor");
} //program continued in next slide
}Java Programming RAGHU ENGINEERING COLLEGE 21
Constructor Overloading: Example
class Addmain
{
public static void main(String args[])
{
Add a1=new Add(); //First constructor is called
Add a2=new Add(47); //Second constructor is called
Add a3=new Add(2,3); //Third constructor is called
}
}
Output:
Addition from first constructor
Value of p:47 from second constructor
Value of c:5 from third constructor

Java Programming RAGHU ENGINEERING COLLEGE 22


Garbage Collection
• Garbage collection is a technique in which object de
allocation is done automatically when no reference to that
object exists.

• In Java, objects are dynamically allocated by using ‘new’


operator. In some languages like C++, dynamically allocated
objects must be manually released by the use of ‘delete’
operator.

• Although Java provides automatic garbage collection, we


can also perform the garbage collection on demand by calling
the gc() and then freeMemory() methods.
Java Programming RAGHU ENGINEERING COLLEGE 23
Garbage Collection: Example
class Memory
{
public static void main(String args[])
{
Runtime r=[Link]();
long mem1,mem2;
Integer ints[]=new Integer[1000];
[Link]("Total memory is:"+[Link]());
[Link]("Initialfreememory:"+[Link]());
[Link]();
mem1=[Link]();
[Link]("Free memory after garbagecollection:"+mem1);
for(int i=0;i<1000;i++)
ints[i]=new Integer(i);
//program continued in next slide
Java Programming RAGHU ENGINEERING COLLEGE 24
Garbage Collection : Example
mem2=[Link]();
[Link]("Free memory after allocation:"+mem2);
for(int i=0;i<1000;i++)
ints[i]=null;
[Link]();
mem2=[Link]();
[Link]("Free memory after collecting discarded
integers:"+mem2);
}
} Output:
Total memory is:62390272
Initial free memory:61089776
Free memory after garbage collection:62102480
Free memory after allocation:61777352
Free memory after collecting discarded integers:62102768
Java Programming RAGHU ENGINEERING COLLEGE 25
Static Keyword
Static keyword:
The static keyword in java is used mainly for memory
management. We can apply java static keyword with
variables, methods and blocks. The static keyword belongs to
the class than instance of the class.

Static method:
A static method is a method that does not act upon
instance variables of a class. Static method is also called as
‘Class method’. A static method is declared by using the
keyword ‘static’. Static methods are called by using the form,
‘class_name.method_name();’
Java Programming RAGHU ENGINEERING COLLEGE 26
Static Keyword
Static variable:
The variables which are declared with the keyword
‘static’ are called static variables. The other name for static
variables is ‘Class variables’.

The reason why static methods cannot act on instance


variables is that JVM first executes the static methods and
then only it creates the objects. Since objects are not available
at the time of calling the static methods, the instance
variables are also not available. We cannot call instance
variable from static method but we can call static variables.
Java Programming RAGHU ENGINEERING COLLEGE 27
Static keyword: Example
class StaticDemo1
{
static int x=56;
static void access()
{
[Link]("x:"+x);
} Output:
} x:56
class StaticMain
{
public static void main(String args[])
{
[Link]();
}
}
Java Programming RAGHU ENGINEERING COLLEGE 28
Static block

A static block is a block of statements which is labeled


with a keyword ‘static’ as below:

static{
//statements
}

As similar to static variables and static methods the


static block will also be executed first.

Java Programming RAGHU ENGINEERING COLLEGE 29


Static block: Example

class StaticDemo2
{
static{
[Link]("Static Block");
} Output:
public static void main(String args[]) Static Block
{ Static Method
[Link]("Static Method");
}
}

Java Programming RAGHU ENGINEERING COLLEGE 30


Static variable used by 2 objects: Example
class Test Test obj1=new Test();
{ Test obj2=new Test();
static int x=10; ++obj1.x;
static void display() [Link]("x in obj1:");
{ [Link]();
[Link](x); [Link]("x in obj2:");
} [Link]();
} }
class StaticDemo }
{ Output:
public static void x in obj1:
main(String args[]) 11
{ x in obj2:
11
Java Programming RAGHU ENGINEERING COLLEGE 31
this keyword
• The keyword ‘this’ refers to the object of the present
working class.

• The keyword ‘this’ is used inside any method to refer the


current object.

• The keyword ‘this’ reference is implicitly used to refer both


the instance variables and methods of current object.

• When an object is created to a class, a default reference is


also created internally to the object that is nothing but ‘this’.
So, ‘this’ can refer to all the things of the present class or
object.
Java Programming RAGHU ENGINEERING COLLEGE 32
this keyword

Ways to use ‘this’:

• Usage with variables, this.variable_name – It refers to the


variable of the class i.e. instance variable

• Usage with methods, this.method_name – It refers to the


method of the class

• Usage as constructor, this() – It refers to the constructor of


the current class.

Java Programming RAGHU ENGINEERING COLLEGE 33


this keyword: Example
class ThisDemo
{ Output:
int len=10;
Value of local variable:40
void method()
Value of instance variable:10
{
int len=40;
[Link](“Value of local variable:”+len);
[Link](“Value of instance variable:”+[Link]);
}
}
Class ThisMain
{
public static void main(String args[])
{
ThisDemo td=new ThisDemo();
[Link]();
}
Java Programming RAGHU ENGINEERING COLLEGE 34
Using this to call constructor: Example
class Sample void access()
{ {
private int x; [Link]("Value of x:"+x);
Sample() }
}
{
class SampleMain
this(55);
{
[Link](); public static void main(String args[])
} {
Sample(int x) Sample s=new Sample();
{ }
this.x=x; }
} Output: Value of x:55

Java Programming RAGHU ENGINEERING COLLEGE 35


Arrays
• An array represents a group of elements of same data type.
It can store a group of elements.

• So, we can store a group of int values as a group or a group


of float values or a group of strings in the array. But we
cannot store some int values and some float values together
in the array.

• In C or C++ by default, arrays are created on static memory


unless pointers are used to create them. In Java, arrays are
created on dynamic memory i.e. memory allotted at run time
by JVM.
Java Programming RAGHU ENGINEERING COLLEGE 36
Arrays
Arrays are generally categorized into two types as described
below:
• Single dimensional (1D) arrays
• Multi dimensional (2D, 3D .etc) arrays

Single Dimensional Array:


A single dimensional array represents a row or a
column of elements.

Creating a single dimensional array:


We can declare a one dimensional array and directly store
elements at the time of it’s declaration as below:
data_type array_name[]={value1, value2…etc};
Java Programming RAGHU ENGINEERING COLLEGE 37
Arrays
Note: Array index starts from 0. So, we can access the first,
second elements as array_name[0], array_name[1]
respectively.

Another way of creating a one dimensional array is by


declaring the array first and then allotting memory for it by
using new operator as below:
data_type array_name[];
array_name=new data_type[size];
This can be written in a single statement as below,
data_type array_name[]=new data_type[size];
Here, size represents the number of elements can be
stored in the array.
Java Programming RAGHU ENGINEERING COLLEGE 38
Arrays
We can store the elements in that array by using static way or
dynamic way as below,
Static way:
array_name[0]=value#1;
array_name[1]=value#2;
:
:
array_name[size-1]=value#size;
Dynamic way:
for(int i=0;i<(size-1);i++)
{
array_name[i]=value; //Here we have to use some
//method to read value
}
Java Programming RAGHU ENGINEERING COLLEGE 39
Arrays
import [Link].*;
class OneDArray
{
public static void main(String args[])
{
Scanner s=new Scanner([Link]);
[Link]("Enter how many subjects you want to
read:");
int n=[Link]();
int marks[]=new int[n];
for(int i=0;i<n;i++)
{
[Link]("Enter marks of subject"+(i+1));
marks[i]=[Link]();
} //program continued in next slide
Java Programming RAGHU ENGINEERING COLLEGE 40
Arrays
int total=0;
for(int i=0;i<n;i++)
{
total+=marks[i];
}
[Link]("Total marks:"+total);
float percent=(float)total/n;
[Link]("Percentage:"+percent);
}
}

The above program prompts the user to enter number of subjects and
marks of each subject, then displays Total marks and percentage of the
student.

Java Programming RAGHU ENGINEERING COLLEGE 41


Two Dimensional Arrays
A two dimensional array represents several rows and columns
of data.

Creating 2D array:
We can declare a 2D array and directly store elements at the
time of declaration as below:
data_type array_name[][]={{value1,value2,...},
{value3,value4,...},
{value5,value6,…}}

In the above syntax the inner curly braces represent the


individual or single row and the number of columns are equal
to the elements in the row.
Java Programming RAGHU ENGINEERING COLLEGE 42
Two Dimensional Arrays

Another way of creating a 2D array is declaring first


array and then allotting memory for it by using new operator.
The form is as below:

data_type array_name[][]=new data_type[r][c];

Here, ‘r’ represents number of rows and ‘c’ represents


number of columns.

Java Programming RAGHU ENGINEERING COLLEGE 43


Two Dimensional Array: Example
class TwoDArray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{4,5,6},{7,8,9}}; Output:
[Link]("Matrix is:");
Matrix is:
for(int i=0;i<3;i++)
1 2 3
{
for(int j=0;j<3;j++) 4 5 6
{ 7 8 9
[Link](arr[i][j]+"\t");
}
[Link]();
}
}
} Java Programming RAGHU ENGINEERING COLLEGE 44
Three Dimensional Arrays
Three dimensional array is a combination of several 2D
arrays.
For example, a college has three departments like ECE,
CSE, EEE then we want to represent the marks obtained by the
students of each department in three different subjects then we can
use 3D array.
Creation of 3D array:
The below is the syntax to be used to creating a 3D array.
data_type array_name[][][]={{{values},{values}},
{{values},{values}},
{{values},{values}}};
Or
data_type array_name[][][]=new data_type[s][r][c];
Java Programming RAGHU ENGINEERING COLLEGE 45
Command line arguments
• Command Line Arguments represents the values passed to
main() method.

• To catch and store the values main() method has a


parameter ‘String args[]’ in ‘public static void main(String
args[])’

• Here, args[] is an array of type String. So, it can store a


group of strings passed to the main() from the command line
interface at the time of running as below:
C:\>java Sample 11 22 java

Java Programming RAGHU ENGINEERING COLLEGE 46


Command line arguments

C:\>java Sample 11 22 java

The three values passed to the main() method of


Sample are 11, 22, java. These three values are automatically
stored as 11 in args[0], 22 in args[1] and java in args[2].

Depending on the number of values passed the JVM


will allot the memory for those values. If no values are
passed then, JVM will not allot any memory.

Java Programming RAGHU ENGINEERING COLLEGE 47


Command line arguments: Example
class CLA
{
public static void main(String args[])
{
String str1=args[0];
String str2=args[1];
[Link]("String 1:"+str1);
[Link]("String 2:"+str2);
}
}
Output:
C:\Users\raghu>java CLA python cpp
String 1:python
String 2:cpp
Java Programming RAGHU ENGINEERING COLLEGE 48
Nested classes
• In java, it is possible to define a class within another class,
such classes are known as nested classes. They enable us to
logically group classes that are only used in one place, thus
this increases the use of encapsulation, and create more
readable and maintainable code.

• The scope of a nested class is bounded by the scope of its


enclosing class.

• A nested class has access to the members, including private


members, of the class in which it is nested. However, reverse
is not true i.e. the enclosing class does not have access to the
members of the nested class.
Java Programming RAGHU ENGINEERING COLLEGE 49
Nested classes
• As a member of its enclosing class, a nested class can be
declared private, public, protected.

Syntax:
class OuterClass
{
:
:
class NestedClass
{
:
:
}
}
Java Programming RAGHU ENGINEERING COLLEGE 50
Nested classes: Example
class Outer class Nested
{ {
public static void main(String[] args)
int x=10;
{
class Inner Outer ob = new Outer();
{ [Link] ib = [Link] Inner();
int x =20; [Link](ib.x);
int y=30; [Link](ob.x);
[Link](ib.y);
}
}
} }
Output:
20
10
30
Java Programming RAGHU ENGINEERING COLLEGE 51

You might also like