SlideShare une entreprise Scribd logo
1  sur  12
JAVA
Topics for Today’s Session
Constructor
Difference between
Method and Constructor
Types of Constructors
Constructors
 A constructor in Java is a special method that is used to
initialize objects.
 The constructor is called when an object of a class is created.
 It can be used to set initial values for object attributes
 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.
 Every time an object is created using the new() keyword, at
least one constructor is called.
Rules for creating Java 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:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Types
of
Constructors
Default Constructor
Parameterized
Constructor
 A constructor that have no parameter is known as default
constructor.
 Default constructor provides the default values to the object like 0,
null etc. depending on the type.
 If there is no constructor in a class, compiler automatically creates a
default constructor.
Syntax :
<class_name>(){ }
// Create a MyClass class
class MyClass {
int n; // Create a class attribute
// Create a class constructor for the MyClass class
public MyClass() {
n = 10; // Set the initial value for the class attribute n
}
public static void main(String[] args)
{
MyClass myObj = new MyClass(); // Create an object of class MyClass
// ( This will call the constructor)
System.out.println(myObj.n); // Print the value of n
}
}
// Outputs
10
Example of default constructor that displays the default values
class Student{
int id;
String name;
void display()
{ System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
} }
Output
0 null
0 null
Explanation:
In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by
default constructor.
Parameterized constructor
 Constructors that have parameters is known as parameterized
constructor.
 Parameterized constructor is used to provide different values to
the distinct objects.
Example of parameterized constructor
/*In this example, we have created the constructor of Student class that
have two parameters. We can have any number of parameters in the
constructor. */
class Student {
int id;
String name;
Student (int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
} }
Difference between constructor and method in java
There are many differences between constructors and methods.
Constructor is used to
initialize the state of an object.
Method is used to expose
behaviour of an object.
Constructor must not have
return type.
Method must have return
type.
Constructor is invoked
implicitly.
Method is invoked explicitly.
The java compiler provides a
default constructor if you don't
have any constructor.
Method is not provided by
compiler in any case.
Constructor name must be
same as the class name.
Method name may or may
not be same as class name.
// Using Constructor
class Car {
int modYr;
String modName;
public Car(int y, String n) {
modYr = y;
modName = n;
}
public static void main(String[] args) {
Car myCar = new Car(1969, "Mustang");
System.out.println(myCar.modYr + " "
+ myCar.modName);
}
}
// Outputs
1969 Mustang
// Using Mathods
class Car {
int modYr;
String modName;
void getdata(int y, String n) {
modYr = y;
modName = n;
}
void show()
{
System.out.println(modYr);
System.out.println(modName);
}
public static void main(String[] args)
{
Car myCar = new Car( )
myCar.getdata(1969, "Mustang");
myCar.show();
}
}
// Outputs
1969
Mustang




Constructor in java

Contenu connexe

Tendances (20)

Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Generics
GenericsGenerics
Generics
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Interface
InterfaceInterface
Interface
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java program structure
Java program structureJava program structure
Java program structure
 
String in java
String in javaString in java
String in java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Java IO
Java IOJava IO
Java IO
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 

Similaire à Constructor in java

constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdfkumari36
 
Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationGeekster
 
Constructor&amp; destructor
Constructor&amp; destructorConstructor&amp; destructor
Constructor&amp; destructorchauhankapil
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop Samad Qazi
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxDrYogeshDeshmukh1
 
Constructors in java
Constructors in javaConstructors in java
Constructors in javasunilchute1
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 

Similaire à Constructor in java (20)

Constructor oopj
Constructor oopjConstructor oopj
Constructor oopj
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdf
 
Constructor
ConstructorConstructor
Constructor
 
Constructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object CreationConstructors In Java – Unveiling Object Creation
Constructors In Java – Unveiling Object Creation
 
Constructor&amp; destructor
Constructor&amp; destructorConstructor&amp; destructor
Constructor&amp; destructor
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Constructor
ConstructorConstructor
Constructor
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 
BCA Class and Object.pptx
BCA Class and Object.pptxBCA Class and Object.pptx
BCA Class and Object.pptx
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
 
Constructors in java
Constructors in javaConstructors in java
Constructors in java
 
Constructors in JAva.pptx
Constructors in JAva.pptxConstructors in JAva.pptx
Constructors in JAva.pptx
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Java Constructor
Java ConstructorJava Constructor
Java Constructor
 

Plus de Madishetty Prathibha

Plus de Madishetty Prathibha (14)

Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Types of datastructures
Types of datastructuresTypes of datastructures
Types of datastructures
 
Introduction to algorithms
Introduction to algorithmsIntroduction to algorithms
Introduction to algorithms
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Java features
Java  features Java  features
Java features
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 

Dernier

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Dernier (20)

Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Constructor in java

  • 2. Topics for Today’s Session Constructor Difference between Method and Constructor Types of Constructors
  • 3. Constructors  A constructor in Java is a special method that is used to initialize objects.  The constructor is called when an object of a class is created.  It can be used to set initial values for object attributes  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.  Every time an object is created using the new() keyword, at least one constructor is called. Rules for creating Java 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
  • 4. Types of Java constructors  There are two types of constructors in Java: 1. Default constructor (no-arg constructor) 2. Parameterized constructor Types of Constructors Default Constructor Parameterized Constructor
  • 5.  A constructor that have no parameter is known as default constructor.  Default constructor provides the default values to the object like 0, null etc. depending on the type.  If there is no constructor in a class, compiler automatically creates a default constructor. Syntax : <class_name>(){ }
  • 6. // Create a MyClass class class MyClass { int n; // Create a class attribute // Create a class constructor for the MyClass class public MyClass() { n = 10; // Set the initial value for the class attribute n } public static void main(String[] args) { MyClass myObj = new MyClass(); // Create an object of class MyClass // ( This will call the constructor) System.out.println(myObj.n); // Print the value of n } } // Outputs 10
  • 7. Example of default constructor that displays the default values class Student{ int id; String name; void display() { System.out.println(id+" "+name); } public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.display(); s2.display(); } } Output 0 null 0 null Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.
  • 8. Parameterized constructor  Constructors that have parameters is known as parameterized constructor.  Parameterized constructor is used to provide different values to the distinct objects. Example of parameterized constructor /*In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. */ class Student { int id; String name; Student (int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]) { Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); s1.display(); s2.display(); } }
  • 9. Difference between constructor and method in java There are many differences between constructors and methods. Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object. Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly. The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name.
  • 10. // Using Constructor class Car { int modYr; String modName; public Car(int y, String n) { modYr = y; modName = n; } public static void main(String[] args) { Car myCar = new Car(1969, "Mustang"); System.out.println(myCar.modYr + " " + myCar.modName); } } // Outputs 1969 Mustang // Using Mathods class Car { int modYr; String modName; void getdata(int y, String n) { modYr = y; modName = n; } void show() { System.out.println(modYr); System.out.println(modName); } public static void main(String[] args) { Car myCar = new Car( ) myCar.getdata(1969, "Mustang"); myCar.show(); } } // Outputs 1969 Mustang