0% found this document useful (0 votes)
6 views24 pages

Understanding Java Constructors and Overloading

Uploaded by

skrewariya2675
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)
6 views24 pages

Understanding Java Constructors and Overloading

Uploaded by

skrewariya2675
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 Constructors

Java Constructors
class Student{
 A special method that is used to initialize int id;
string name;
objects. void display(){
 It is called when an object of a class is [Link](“Id=”+id+”Name=”+name

created (using the new keyword). public static void main(String args[]){
Student s1=new Student();
 Sets initial values to the objects. Student s2=new Student();
 Java provides default constructors. But, [Link]();
[Link]();
customized constructors can be created. }
}
Rules for Creating Constructors

1. Constructor name must be the same as its class name.


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
synchronized

Note :
If no constructor is created, Java calls its default constructor
Types of Constructors

No argument Parameterized
Copy Constructor
constructor Constructor
Types of Constructor –No argument
Constructor
class Student{
int id;
string name;
Student(){
[Link](“Student object created”);
}
void display(){
[Link](“Id=”+id+”Name=”+name);

public static void main(String args[]){


Student s=new Student();
[Link]();

}
}
Parameterized Constructor
class Student{
 Takes multiple parameters. int id;
string name;
 Used to initialize object Student(int i, string n){
attributes with different id=i;
values. name=n;
[Link](“Student object created”);

}
void display(){
[Link](“Id=”+id+”Name=”+name);

public static void main(String args[]){


Student s=new Student(5, “Arijit”);
[Link]();

}
}
Private Constructor

class A{
private A(){}
void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
}
}
Use of private constructor

Case 1 : Sometimes we don’t want object creation. But, class’s


functions can be used if they are used as static methods. Here, we
can’t create object, but you can call [Link](5)

class MathUtil
{
private MathUtil() { // prevent instantiation }
public static int square(int x) {
return x * x;
}
}
Use of private constructor

Case 2 : Creating Singleton object i.e., to ensure that only one object
of the class exists. Can be created using [Link]()

class Singleton {
private static Singleton instance;
private Singleton() {….}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
Java Method Overloading

Class having multiple method with same name but


different in parameters.
Improves readability.
Two ways of method overloading
➢Changing the number of arguments
➢By changing the data types
Changing the Number of Arguments

class Adder{
 Two different add functions
static int add(int a,int b){return a+b;}
with 2 and 3 parameters.
static int add(int a,int b,int c){return a+b+c;}
 Example shows static }
methods for simplicity as no
object creation is required. class FuncOverloading{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
Changing the data type of arguments

class Adder{
static int add(int a,int b){return a+b;}
static float add(float a, float b){return a+b;}
}

class FuncOverloading{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](5.6, 3.5));
}
}
Why method overloading is not possible
by changing only the return type?
In Java, method overloading is determined by
the method signature, which consists of:
Method name and Parameter list (types,
number, and order)

Return type is NOT part of the method


signature.
Can the main() method in Java be
overloaded?
Can the main() method in Java be
overloaded?

Yes, 1) But how?


2) But JVM calls always the default
main i.e., main(String[] args)
public class MainMethodOverload {
//Overloaded main() method 1
public static void main(int n) {
[Link](n);
}

//Original main() method


public static void main(String[] args)
{
[Link]("Original main() method executed");
//invoking overloaded main()
[Link](112);
}
}
Narrowing and Widening in Java
 When we assign one data type to another, Java may need to convert
values.
Widening Conversion (Implicit Casting)
✓ Converting a smaller data type → larger data type.
✓ Safe, because there’s no data loss.
✓ Done automatically by Java (no explicit cast needed).
Example
int x=10;
double y=x; //int 32 bits is converted to double 64 bits
Order of widening
byte → short → int → long → float → double
char → int → long → float → double
Narrowing
 Converting a larger data type → smaller data type.
 Risky, because data may be lost or changed.
 Requires explicit cast using (type).

double a = 9.78;
int b = (int) a; // double → int (narrowing)
[Link](b); // 9 (decimal part lost)
Method Overload+Type casting

When we call an overloaded method, the compiler decides


which version to call based on the argument types.
If there isn’t an exact match, Java applies type conversion
rules.
Case 1 : Widening (Automatic Promotion)
class Test {
void show(int x) { [Link]("int version"); }
void show(double x) {[Link]("double version"); }

public static void main(String[] args) {


Test t = new Test();
[Link](10); // int literal → exact match
[Link](10.5f); // float → widened to double
}
}

Output: int version


double version
Case 2: Narrowing (Needs Explicit Cast)

class Test {
void show(int x) { [Link]("int version");
}
public static void main(String[] args) {
Test t = new Test();
// [Link](3.5); // ERROR: double → int
[Link]((int) 3.5); // Works with explicit cast
}}

Output: int version


double version
Java Constructor Overloading

It is a technique of having multiple constructors


with different parameter list.
Each constructor performs a different task.
Differentiated by the compiler by number/type of
parameters.
class Student{
int id;
string name;
Student(){[Link](“Default Constructor”);}

Student(int i){
id=i;
[Link](“Constructor 2”); }

Student(int i, string n){


id=i;
name=n;
[Link](“Constructor 3”);}

public static void main(String args[]){


Student s1=new Student();
Student s2=new Student(5);
Student s3=new Student(5, “Arijit”);

}
}

You might also like