0% found this document useful (0 votes)
12 views

Unit 2.pptx

The document provides an overview of classes and objects in Java, detailing the definition of a class, instance variables, methods, constructors, and method overloading. It explains how to create and initialize objects, the types of constructors, and the use of the 'this' keyword to resolve ambiguity. Additionally, it covers static members, garbage collection, and the advantages of memory efficiency in Java programming.

Uploaded by

newmovies1638
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)
12 views

Unit 2.pptx

The document provides an overview of classes and objects in Java, detailing the definition of a class, instance variables, methods, constructors, and method overloading. It explains how to create and initialize objects, the types of constructors, and the use of the 'this' keyword to resolve ambiguity. Additionally, it covers static members, garbage collection, and the advantages of memory efficiency in Java programming.

Uploaded by

newmovies1638
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
You are on page 1/ 32

Unit 2

Classes and Objects


Defining class
In object-oriented programming, a class is a basic building block. It can be defined as
template that describes the data and behaviour associated with the class instantiation.
Instantiating is a class is to create an object (variable) of that class that can be used to
access the member variables and methods of the class.
Java provides a reserved keyword class to define a class. The keyword must be followed
by the class name. Inside the class, we declare methods and variables.
In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by convention).
4. Body: The class body surrounded by braces, { }.
Syntax:
<access specifier> class class_name

{
// member variables
// class methods
}
Instance variable
○ The variables that are declared inside the class but outside the scope of any
method are called instance variables in Java.
○ The instance variable is initialized at the time of the class loading or when an
object of the class is created.
○ An instance variable can be declared using different access modifiers available
in Java like default, private, public, and protected.
○ To use an instance variable an object of the class must be created.
○ An instance variable is destroyed when the object it is associated with is
destroyed.
Example:
public class Studentsrecords
{
/* declaration of instance variables. */
String name;
String division;
int age;
}
Instance method
The method declaration provides information about method attributes, such
as visibility, return-type, name, and arguments. It has six components that
are known as method header.
Syntax:
returnType methodName() {
// method body
}
Method declaration
Method Signature: Every method has a method signature. It is a part of the
method declaration. It includes the method name and parameter list.
● returnType - It specifies what type of value a method returns For example if a
method has an int return type then it returns an integer value. If the method
does not return a value, its return type is void.
● Method Name: It is a unique name that is used to define the name of a
method. It must be corresponding to the functionality of the method. Suppose,
if we are creating a method for subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its name.
● Parameter List: It is the list of parameters separated by a comma and enclosed
in the pair of parentheses. It contains the data type and variable name. If the
method has no parameter, left the parentheses blank.
● Method Body: It is a part of the method declaration. It contains all the actions
to be performed. It is enclosed within the pair of curly braces.
Creating and initializing object from class
Using the new keyword is the most popular way to create an object or
instance of the class. When we create an instance of the class by using the
new keyword, it allocates memory (heap) for the newly created object and
also returns the reference of that object to that memory.

Syntax for creating an object:


ClassName object = new ClassName();
Programs based on Instance variable and Instance method refer
Practical 3a and extra programs.
Constructors
A constructor is similar to a method that is invoked when an object of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and does not
have any return type.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
Example:
class Test {
Test() {
// constructor body
}
}
Example:
class ConstructorDemo {
private String name;

// constructor
ConstructorDemo() {
System.out.println("Constructor Called:");
name = "SYIT-CS";
System.out.println("The name is " + name);
}
public static void main(String[] args) {

// constructor is invoked while creating an object of the Main class


ConstructorDemo obj = new ConstructorDemo();
//System.out.println("The name is " + obj.name);
}
}
Types of Constructor

In Java, constructors can be divided into 3 types:

1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
Java No-Arg Constructors
Similar to methods, a Java constructor may or may not have any parameters
(arguments).

If a constructor does not accept any parameters, it is known as a no-argument


constructor. For example,

Constructor() {

// body of the constructor

}
Example:
class Company {
String name;
// public constructor
public Company() {
name = "ABC";
}
}
class NoargExample {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructor with parameters).
class Demo{
String languages;
// constructor accepting single value
Demo(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Demo obj1 = new Demo("Java");
Demo obj2 = new Demo("Python");
Demo obj3 = new Demo("C");
}
}
Java Default Constructor

If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.
example:
class DefaultDemo {
int a;
boolean b;
public static void main(String[] args) {

// A default constructor is called


DefaultDemo obj = new DefaultDemo();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Method Overloading
In Java, two or more methods may have the 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) { ... }
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.

The better way to accomplish this task is by overloading methods. And, depending upon
the argument passed, one of the overloaded methods is called. This helps to increase the
readability of the program.
Overloading by changing the number of parameters
class MethodOverloading {
void display(int a){
System.out.println("Arguments: " + a);
}
void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
MethodOverloading obj=new MethodOverloading();
obj.display(1);
obj.display(1, 4);
}
}
Method Overloading by changing the data type of parameters
class MethodOverloading {
// this method accepts int
void display(int a){
System.out.println("Got Integer data.");
}
// this method accepts String object
void display(String a){
System.out.println("Got String object.");
}
public static void main(String[] args) {
MethodOverloading obj=new MethodOverloading();
obj.display(1);
obj.display("Hello");
}
this keyword
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
this: to refer current class instance variable
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;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}

}
class TestThis1{

public static void main(String args[]){


Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);


s1.display();
s2.display();

}}
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;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
static members of a class
Variables and methods declared using keyword static are called static members of a
class.
You know that non-static variables and methods belong to instance.
But static members (variables, methods) belong to class.
Static members are not part of any instance of the class.
Static members can be accessed using class name directly, in other words, there is
no need to create instance of the class specifically to use them.
Static members can be of two types:
#Static Variables
#Static Methods
Whenever a variable is declared as static, this means there is only one copy of it for
the entire class, rather than each instance having its own copy.
A static method means it can be called without creating an instance of the class.
Static variables and methods in Java provide several advantages, including memory
efficiency, global access, object independence, performance, and code
organization.
Example:
class Student
{ private static int count=0; //static variable
Student()
{
count++; //increment static variable
}
static void showCount() //static method
{
System.out.println(“Number Of students : “+count);
}
}
public class StaticDemo {
public static void main(String[] args) {
Student s1=new Student();
Student s2=new Student();
Student.showCount(); //calling static method
}}
Garbage collection
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.
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.

How can an object be unreferenced?

○ By nulling the reference


○ By assigning a reference to another
○ By anonymous object

You might also like