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

Class - Constructor This

Classes and Objects provides definitions and examples of key object-oriented programming concepts in Java, including: 1. A class defines fields (data members) and methods that represent the properties and behaviors of an object; classes are templates used to create objects with memory allocated to store the field values. 2. An object is an instance of a class that stores the field values; objects are created using the new operator and allow accessing class members through dot notation. 3. Constructors initialize an object and are invoked when an object is created; they can be default, parameterized, or overloaded. Methods can also be overloaded to increase readability and allow compile-time polymorphism. 4. The this keyword refers

Uploaded by

guru cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Class - Constructor This

Classes and Objects provides definitions and examples of key object-oriented programming concepts in Java, including: 1. A class defines fields (data members) and methods that represent the properties and behaviors of an object; classes are templates used to create objects with memory allocated to store the field values. 2. An object is an instance of a class that stores the field values; objects are created using the new operator and allow accessing class members through dot notation. 3. Constructors initialize an object and are invoked when an object is created; they can be default, parameterized, or overloaded. Methods can also be overloaded to increase readability and allow compile-time polymorphism. 4. The this keyword refers

Uploaded by

guru cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

Classes and Objects :

A class is a important building block of object oriented programming language. A


class is a group of fields and methods. Fields are also called data members of a
class. A method manipulates the data stored in the fields of the class.

General form of class is given below.


class classname
{
Type instance variable 1;
“ ‘’ ‘’ 2;
Type instance variable N;
Type method name1(parameters)
{
Body of method1;
}
Type method name2(parameters)
{
Body of method2;
}
}
Data members defined in a class are called instance variable. The code is present
within method. The collection of the data members and methods are called
member of class.

Example of creation of class:

class Rectangle
1
{

double length ;

double breadth;

void read(double l, double b)

length=l;

breadth=b;

void find area( )

double area = length *breadth;

System.out.println(*Area is “+area);

A class with datamembers and methods has no life and memory is not allocated
to data members with class template or class structure declaration. So, we have
to use objects to allocate a memory to data members of class.

Creating an object:

Instance of a class is called an object. creating an object is called instantiating an


object. Object in java is created by using new operator.

The new operator creates an object of the specified class and returns a reference
to the object.

Syntax:
2
Declare the object and allocate memory by using new operator

classname object name=new classname( );

Ex: Rectangle r1=new Rectangle( );

Accessing class members:

We should establish a relation between objectname and members to access the


class members from main( ) method.

Syntax: objectname.member;

Ex: r1.find area( );

Total program of class structure:

class Rectangle

double length ;

double breadth;

void read(double l, double b)

length=l;

breadth=b;

void find area( )

double area = length *breadth;

System.out.println(*Area is “+area);
3
}

class Rectangledemo
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.read(11,5);
r2.read(3,15);
r1.findarea( );
r2.findarea( );
}
}
Constructors:
Constructor is a special type of method that is used to initialize the object.
Constructors are invoked automatically when objects are created.
Rules for creating constructor:
In order to create a constructor we have to observe following rules
 Constructor name must be similar to class name.
 It should be declared as public.
 They do not have any return types even void.
 Constructor can be overloaded.
 Constructor cannot be inherited.
There are two different types of constructors available in java. they are
1).Default constructor
2).Parameterized constructor
Default constructor: A constructor that can accepts no parameters is called Default
constructor . (OR)
A constructor without any parameters is called Default constructor.
If no constructor is defined for a class then java system automatically generates a special
constructor called default constructor.
Syntax:

4
class classname
{
classname ( )
{
Statements ;
}
----------
----------
}
Example:
class triangle

double base;

double height;

triangle( )

base=10.54;

height=20.68;

void findarea( )

double area = 0.5 * base * height;

System.out.println("Area is "+area);

class triangledefault

public static void main(String args[ ])

triangle t1=new triangle();

5
t1.findarea();

triangle t2=new triangle();

t2.findarea();

disadvantage:

defalt constructor is always initialized with constant values.

note: If there is no constructor in a class, compiler automatically creates a default constructor.

Parameterized Constructor: A constructor which receives parameters from outside is called


Parameterized constructor. OR

A constructor that have parameters is known as parameterized constructor .

In order to initialize an object with various values we have to use the Parameterized
constructor.

Syntax:

class classname

classname (parameters )

Statements ;

----------

---------

Example:

6
class triangle

double base ;

double height;

triangle (double b, double h)

base = b;

height = h;

void findarea( )

double area = 0.5*base *height;

System.out.println ("Area is "+area);

class triangleparameter

public static void main(String args[])

triangle t1=new triangle(10.52,20.72);

t1.findarea();

triangle t2=new triangle(32.37,20.67);

t2.findarea();

}
7
Constructor Overloading in Java:
Defining two or more constructors with same name in a class but with different
signature by changing either number of parameters or type of parameters is
known as constructor Overloading. OR
Constructor overloading is a technique in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these
constructors by taking into account the number of parameters in the list and their
type.

class triangle
{
double base ;
double height;
triangle( )
{
base=10.5;
height=20.8;
}

triangle (double b, double h)


{
base = b;
height = h;
}
void findarea( )
{
double area = 0.5*base *height;
System.out.println ("Area is "+area);
}
}

class triangleconover
{
public static void main(String args[])
{
8
triangle t1=new triangle();
t1.findarea();
triangle t2=new triangle(32.37,20.67);
t2.findarea();
}
}

Method Overloading in Java :


Defining two or more methods with same name in a class but with different
signature by changing either number of parameters or type of parameters is
known as Method Overloading.
Advantage of method overloading?
Method overloading increases the readability of the program.
Java achieves compile time polymorphism by using Method overloading concept.
Different ways to overload the method
There are two ways to overload the method in java.
1. By changing number of parameters
2.By changing the data type of parameters

In java, Methood Overloading is not possible by changing the return type of the
method.

1)Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.

class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}

public static void main(String args[])


{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}
9
2)Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differs in data type. The first
sum method receives two integer arguments and second sum method receives two double
arguments.
class Calculation2
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}

public static void main(String args[])


{
Calculation2 obj=new Calculation2();
obj.sum(10.25,10.45);
obj.sum(20,30);

}
}

this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.

Usage of java this keyword


 this keyword can be used to refer current class instance variables.
 this() can be used to invoke current class constructor.
 this keyword can be used to invoke current class method (implicitly)

The this keyword can be used to refer current class instance variable.
 Whenever data members (instance variables) and local parameters with same name
then java compiler gets an ambiguity and parameters are not assigned to data
members.

 Whenever data members (instance variables) and local parameters with same name
then data members are referred by using this keyword or this pointer .

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below.
10
class Student
{
int id;
String name;

Student(int id,String name)


{
id = id;
name = name;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student s1 = new Student(101,"ANIL");
Student s2 = new Student(102,"RAJU");
s1.display();
s2.display();
}
}
Output:0 null
0 null

In the above example, parameters (formal arguments) and instance variables are with same
name that is why we are using this keyword to distinguish between local variables and instance
variables.

Solution of the above problem by this keyword

class Student
{
int id;
String name;

Student(int id,String name)


{
this.id = id;
this.name = name;
}
11
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student(101,"ANIL");
Student s2 = new Student(102,"RAJU");
s1.display();
s2.display();
}
}
Output 101 ANIL
102 RAJU
If local variables(formal arguments) and instance variables are with different
names , there is no need to use this keyword.

Program where this keyword is not required


class Student
{
int id;
String name;

Student12(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student e1 = new Student12(101,"ANIL");
Student e2 = new Student12(102,"RAJU");
e1.display();
e2.display();
}
}
Output 101 ANIL
102 RAJU

12
this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor
chaining).

This approach is better if you have many constructors in the class and want to reuse that
constructor.

class Student13
{
int id;
String name;

Student13()
{
System.out.println("default constructor is invoked");
}

Student13(int id,String name)


{
this (); //it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student13 e1 = new Student13(101,"ANIL");
Student13 e2 = new Student13(102,"RAJU");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
101 ANIL

13
102 RAJU

The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method

class S
{
void m()
{
System.out.println("method is invoked");
}
void n()
{
this.m(); //no need
}
void p()
{
n(); //complier will add this to invoke n() method as this.n()
}
public static void main(String args[])
{
S s1 = new S();
s1.p();
}
}

14

You might also like