0% found this document useful (0 votes)
11 views73 pages

Java Classes and Object Creation Guide

The document provides an overview of Java programming, focusing on classes and objects, including their definitions, creation, and usage. It explains various concepts such as instance variables, methods, constructors, method overloading, and the static keyword, along with examples to illustrate these concepts. Additionally, it covers the use of the 'this' keyword to resolve naming conflicts between instance variables and parameters.

Uploaded by

Amruta Sawakar
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)
11 views73 pages

Java Classes and Object Creation Guide

The document provides an overview of Java programming, focusing on classes and objects, including their definitions, creation, and usage. It explains various concepts such as instance variables, methods, constructors, method overloading, and the static keyword, along with examples to illustrate these concepts. Additionally, it covers the use of the 'this' keyword to resolve naming conflicts between instance variables and parameters.

Uploaded by

Amruta Sawakar
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

JAVA Programming

Unit II

Class & Objects


By Prof: Santosh .B
ARJ BCA College Ilkal
Java Classes

• Java is an object-oriented programming language.


• Everything in Java is associated with classes and
objects, along with its attributes and methods.
For example: in real life, a car is an object. The car
has attributes, such as weight and color,
and methods, such as drive and brake.
• A Class is like an object constructor, or a
"blueprint" for creating objects.
Create a Class
• To create a class, use the keyword class
• A class is a blueprint from which individual
objects are created.
• Following is a sample of a class
Syntax to declare a class:
class <class_name>{
field;
method;
}
public class Dog
{
String breed;
int age;
String color;
void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}

A class can have any number of methods to access the value of various
kinds of methods. In the above example, barking(), hungry() and
sleeping() are methods.
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 variables − Class variables are variables declared
within a class, outside any method, with the static
keyword.
Define class with instance variables and
methods
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.
public class Dog {
String breed;
int age;
String color;

static void barking() {


[Link]("doggy barking");
}
static void sleeping() {
[Link]("nayiii malkondaiti");
}

static void getBreed( String breed){


[Link]("The dog breed is "+breed);
}

public static void main(String args[]){


barking();
hungry();
getBreed("mudhol");
}
}
Object creation,
a class provides the blueprints for objects. So basically, an
object is created from a class. In Java, the new keyword
is used to create new objects.
There are three steps when creating an object from a
class −
• Declaration − A variable declaration with a variable
name with an object type.
• Instantiation − The 'new' keyword is used to create the
object.
• Initialization − The 'new' keyword is followed by a call
to a constructor. This call initializes the new object.
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
int id;
String name;
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
[Link]([Link]);
[Link]([Link]);
}
}
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.
public class Student
{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
[Link]=101;
[Link]=“sharan";
[Link]([Link]+" "+[Link]);//printing
members with a white space
}
}
We can also create multiple objects and store information in it through
reference variable.
public class Student{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]=102;
[Link]="Monoo";
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
}
}
Accessing member of class
Java classes consist of various variables and instance members
(or methods). Before accessing class members in Java like
variables and instance members, it is essential to declare
them. So, let us first understand how to declare variables
and methods.
Instance variables and methods are accessed via objects with
the help of a dot (.) operator. The dot operator creates a
link between the name of the instance variable and the
name of the class with which it is used.

[Link] = 10000;
Where, s is the name of the object and basicsal is the instance
variable.
class Employee
{
String name;
int age;
float bsal, gsal;
public void acceptDetails(String n, int a, int s)
{
name = n;
age = a;
bsal = s;
}
public void showData()
{
[Link]("Employee Name = " + name);
[Link]("Employee Age = " + age);
[Link]("Employee Basic Salary = " + bsal);
}
public static void main(String args [])
{
Employee e1 = new Employee(); // object e1 created
[Link]("Nancy", 28, 12000);
[Link]();
}
}
Java Program Calculate Area of Rectangle

class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea()
{
[Link](length*width);
}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
[Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}
}
Argument passing
• Information can be passed to methods as parameter.
Parameters act as variables inside the method.
• Parameters are specified after the method name,
inside the parentheses. You can add as many
parameters as you want, just separate them with a
comma.
The following example has a method that takes
a String called fname as parameter. When the method
is called, we pass along a first name, which is used
inside the method to print the full name:
public class Main
{
static void myMethod(String fname)
{
[Link](fname + " good");
}
public static void main(String[] args)
{
myMethod(“Rama");
myMethod(“Raheem");
}
}
When a parameter is passed to the method, it is called
an argument. So, from the example above: fname is
a parameter, while Rama & Raheem are arguments.
Multiple Parameters
• You can have as many parameters as you like:
public class Main
{
static void myMethod(String fname, int age)
{
[Link](fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Note that when you are working with multiple parameters, the method call
must have the same number of arguments as there are parameters, and
the arguments must be passed in the same order.
Return Values
• The void keyword, used in the examples
above, indicates that the method should not
return a value. If you want the method to
return a value, you can use a primitive data
type (such as int, char, etc.) instead of void,
and use the return keyword inside the
method:
public class Main {
static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


[Link](myMethod(3));
}
}
Constructors
• In Java, a constructor is a block of codes similar to
the method. It is called when an instance of
the class is created. At the time of calling
constructor, memory for the object is allocated in
the memory.
• 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.
• Constructor name must be the same as its
class name
• A Constructor must have no explicit return
type
• A Java constructor cannot be abstract, static,
final, and synchronized
Types of Java constructors
There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor
Example of default constructor
In this example, we are creating the no-arg constructor in the
Bike class. It will be invoked at the time of object creation.
class Bike1{
Bike1()
{
[Link]("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
2. 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(){[Link](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
[Link]();
[Link]();
}
}
Method overloading
In Java, two or more methods can have same name if
they differ in parameters (different number of
parameters, different types of parameters, or both).
These methods are called overloaded methods and this
feature is called method overloading.
For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
• Here, the func() method is overloaded. These
methods have the same name but accept
different arguments.
• Notice that, the return type of these methods
is not the same. Overloaded methods may or
may not have different return types, but they
must differ in parameters they accept.
Why method overloading?
• Suppose, you have to perform the addition of given
numbers but there can be any number of arguments
(let’s say either 2 or 3 arguments for simplicity).
• In order to accomplish the task, you can create two
methods sum2num(int, int) and sum3num(int, int,
int) for two and three parameters respectively.
However, other programmers, as well as you in the
future may get confused as the behavior of both
methods are the same but they differ by name.
1. Overloading by changing the number of arguments
class MethodOverloading
{
private static void display(int a)
{
[Link]("Arguments: " + a);
}
private static void display(int a, int b)
{
[Link]("Arguments: " + a + " and " + b);
}
public static void main(String[] args)
{
display(1);
display(1, 4);
}
}
[Link] changing the datatype of parameters
class MethodOverloading
{
// this method accepts int
private static void display(int a)
{
[Link]("Got Integer data.");
} // this method accepts String object
private static void display(String a)
{
[Link]("Got String object.");
}
public static void main(String[] args)
{
display(1);
display("Hello");
}
}
Java static keyword

The static keyword in Java is used for memory


management mainly. We can apply static
keyword with variables, methods, blocks
and nested classes. The static keyword
belongs to the class than an instance of the
class.
1) Java static variable
• If you declare any variable as static, it is known as a
static variable.
• The static variable can be used to refer to the common
property of all objects (which is not unique for each
object), for example, the company name of employees,
college name of students, etc.
• The static variable gets memory only once in the class
area at the time of class loading.
Advantages of static variable
• It makes your program memory efficient (i.e., it saves
memory).
Syntax : static variable
static int a = 10;
static int b;
Static variables
• When a variable is declared as static, then a
single copy of variable is created and shared
among all objects at class level. Static
variables are, essentially, global variables. All
instances of the class share the same static
variable.
Static Methods − You can create a static method by using the
keyword static. Static methods can access only static fields,
methods. To access static methods there is no need to instantiate
the class, you can do it just using the class name as −

public class MyClass {


public static void sample()
{
[Link]("Hello");
}
public static void main(String args[])
{
[Link]();
}
}
Static Fields − You can create a static field by using the
keyword static. The static fields have the same value in
all the instances of the class. These are created and
initialized when the class is loaded for the first time.
Just like static methods you can access static fields
using the class name (without instantiation).
public class MyClass
{
public static int data = 20;
public static void main(String args[]){
[Link]([Link]);
}
}
Static Blocks − These are a block of codes with a static
keyword. In general, these are used to initialize the
static members. JVM executes static blocks before the
main method at the time of class loading
public class MyClass
{
static
{
[Link]("Hello this is a static block");
}
public static void main(String args[]){
[Link]("This is main method");
}
}
This keyword
What is this Keyword in Java?
• this keyword in Java is a reference variable that refers to
the current object of a method or a constructor. The main
purpose of using this keyword in Java is to remove the
confusion between class attributes and parameters that
have same names.
Following are various uses of 'this' keyword in Java:
• It can be used to refer instance variable of current class
• It can be used to invoke or initiate current class constructor
• It can be passed as an argument in the method call
• It can be passed as argument in the constructor call
• It can be used to return the current class instance
• The this keyword can be used to refer current
class instance variable. If there is ambiguity
between the instance variables and
parameters, this keyword resolves the
problem of ambiguity.
• Understanding the problem without this
keyword
class Student{
int rollno;
String name;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit");
Student s2=new Student(112,"sumit“);
[Link]();
[Link]();
}}
Output:
0 null 0.0
0 null 0.0
• In the above example, parameters (formal
arguments) and instance variables are same.
So, we are using this keyword to distinguish
local variable and instance variable.
• Solution of the above problem by this
keyword
class Student{
int rollno;
String name;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
}
void display(){
[Link](rollno+" "+name+" "+fee);
}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit”);
Student s2=new Student(112,"sumit");
[Link]();
[Link]();
}}
Output:
111 ankit
112 sumit

If local variables(formal arguments) and instance variables are


different, there is no need to use this keyword like in the
following program:
Garbage collection & finalize() method
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming
the runtime unused memory automatically. In
other words, it is a way to destroy the unused
objects.
• To do so, we were using free() function in C
language and delete() in C++. But, in java it is
performed automatically. So, java provides
better memory management.
Advantage of Garbage Collection
• It makes java memory efficient because
garbage collector removes the unreferenced
objects from heap memory.
• It is automatically done by the garbage
collector(a part of JVM) so we don't need to
make extra efforts.
• Main objective of Garbage Collector is to free
heap memory by destroying unreachable
objects.
How can an object be unreferenced?
There are many ways:
• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
//now the first object referred by e1 is available for
garbage collection
3) By anonymous object:
new Employee();
gc() method
• The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
//Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize()
{
[Link]("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
}
}
Output:
object is garbage collected
object is garbage collected

finalize() method
• The finalize() method is invoked each time before the
object is garbage collected. This method can be used to
perform cleanup processing. This method is defined in
Object class as:
• finalize() method is present in Object class with following
prototype.
protected void finalize() throws Throwable
protected void finalize(){}
Why finalize method is used()?
finalize() method releases system resources
before the garbage collector runs for a specific
object. JVM allows finalize() to be invoked only
once per object.
Nested & Inner classes
• In Java, it is also possible to nest classes (a
class within a class). The purpose of nested
classes is to group classes that belong
together, which makes your code more
readable and maintainable.
• To access the inner class, create an object of
the outer class, and then create an object of
the inner class:
Syntax
• Following is the syntax to write a nested class.
Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
class Outer_Demo
{
class Inner_Demo
{
}
}
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.
Inner Class
• Creating an inner class is quite simple. You just
need to write a class within a class. Unlike a
class, an inner class can be private and once
you declare an inner class private, it cannot be
accessed from an object outside the class.
• Following is the program to create an inner
class and access it. In the given example, we
make the inner class private and access the
class through a method.
class OuterClass
{
int x = 10;
class InnerClass
{
int y = 5;
}

}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
[Link] myInner = [Link] InnerClass();
[Link](myInner.y + myOuter.x);
}
} // Outputs 15 (5 + 10)
class Outer_Demo
{
int num;
private class Inner_Demo {
public void print() {
[Link]("This is an inner class");
}
} // Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
[Link]();
}
}
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner(); } }
Wrapper Classes
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.
• A Wrapper class is a class whose object wraps or contains
primitive data types. When we create an object to a
wrapper class, it contains a field and in this field, we can
store primitive data types. In other words, we can wrap a
primitive value into a wrapper class object.
Need of Wrapper Classes
• They convert primitive data types into objects.
Objects are needed if we wish to modify the
arguments passed into a method (because
primitive types are passed by value).
• The classes in [Link] package handles only
objects and hence wrapper classes help in this
case also.
Autoboxing
• The automatic conversion of primitive data
type into its corresponding wrapper class is
known as autoboxing, for example, byte to
Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
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=[Link](a);
//converting int into Integer explicitly
Integer j=a;
//autoboxing, now compiler will write [Link](a) internally

[Link](a+" "+i+" "+j);


}}
Output:
20 20 20
Unboxing
• The automatic conversion of wrapper type
into its corresponding primitive type is known
as unboxing. It is the reverse process of
autoboxing. Since Java 5, we do not need to
use the intValue() method of wrapper classes
to convert the wrapper type into primitives.
Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=[Link](); //converting Integer to int explicitly
int j=a;
//unboxing, now compiler will write [Link]() internally

[Link](a+" "+i+" "+j);


}
}

Output:
333
Java Wrapper classes Example
public class WrapperExample3{
public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
//Printing objects
[Link]("---Printing object values---");
[Link]("Byte object: "+byteobj);
[Link]("Short object: "+shortobj);
[Link]("Integer object: "+intobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;

//Printing primitives
[Link]("---Printing primitive values---");
[Link]("byte value: "+bytevalue);
[Link]("short value: "+shortvalue);
[Link]("int value: "+intvalue);
}
}
Output:
---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
Strings in Java

• Strings in Java are Objects that are backed


internally by a char array. Since arrays are
immutable(cannot grow), Strings are immutable
as well. Whenever a change to a String is made,
an entirely new String is created.
• Below is the basic syntax for declaring a string
in Java programming language.
Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;
Example: String str = "Geeks";
StringName = new String (“string”);
Example: String s1 = new String(“ARJBCA");
import [Link].*;
import [Link].*;

class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = “ARJ BCA";

// Prints the String.


[Link]("String s = " + s);

// Declare String using new operator


String s1 = new String(" ARJ BCA ");

// Prints the String.


[Link]("String s1 = " + s1);
}
}
Output:
String s = GeeksforGeeks
String s1 = GeeksforGeeks
StringBuffer: StringBuffer is a peer class of String that provides
much of the functionality of strings. String represents fixed-
length, immutable character sequences while StringBuffer
represents growable and writable character sequences.
Syntax:StringBuffer s = new StringBuffer(“ARJBCACOLLEGE");
StringBuilder: The StringBuilder in Java represents a mutable
sequence of characters. Since the String Class in Java creates
and immutable sequence of characters, the StringBuilder class
provides an alternate to String Class, as it creates a mutable
sequence of characters.
Syntax: StringBuilder str = new StringBuilder(); [Link]("GFG");
String Arrays
We can also create and use arrays that contain strings. The
statement
• Java String array is basically an array of objects.
• There are two ways to declare string array – declaration
without size and declare with size.
• There are two ways to initialize string array – at the time of
declaration, populating values after declaration.
Java String Array Declaration

String[] strArray; //declare without size


String[] strArray1 = new String[3]; //declare with size
It will create an strArray1 array of size 3 to hold three string
//inline initialization
String[] strArray1 = new String[] {"A","B","C"};
String[] strArray2 = {"A","B","C"};

//initialization after declaration String[]


strArray3 = new String[3];
strArray3[0] = "A";
strArray3[1] = "B";
strArray3[2] = "C";
String methods

You might also like