SlideShare a Scribd company logo
Constructors, Overloading and
Static Members
1
Constructors
 Java allows objects to initialize themselves when
they are created through the use of a constructor.
 Constructors play the role of initializing objects
 Constructors are a special kind of methods that are
invoked using the new operator when an object is
created.
Constructors, cont.
 Constructors have following properties:
 Constructors must have the same name as the class itself.
 Constructors do not have a return type— not even void.
 The implicit return type is class itself
 A constructor with no parameters is referred to as a
default constructor and constructor with parameters is
called as parameterized constructor
3
Program for constructor
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo1 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(); //constructor invoked
Box mybox2 = new Box(); //constructor invoked
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
4
Parameterized Constructors
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo2 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
5
Exercise
 WAP to create class rectangle and calculate
area and perimeter of it by using constructor.
 WAP to create class Employee. Add methods
to read and display employee information by
using constructor such as id and salary.
6
Method Overloading
 Two or more methods within the same class that have the
same name but methods must differ in the type and/or
number of their parameters.
 Method overloading is one of the ways that Java implements
polymorphism
 When an overloaded method is invoked, Java uses the type
and/or number of arguments to determine which version of
the overloaded method to actually call.
7
Example
class OverloadDemo {
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}
8
Constructor Overloading
 Similar to method overloading we can also overload
constructor .
 Overloaded constructors have the same name but must differ
in the type and/or number of their parameters.
9
Example
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
10
Exercise
 WAP to overload add method to perform
addition of two integers, addition of three
integers and addition of two float numbers.
 WAP to create overloaded constructor to
calculate area of triangle ,rectangle and circle.
11
Using Objects as Parameters
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
void add(Test o) {
if(o.a == a && o.b == b)
System.out.println(" Equal”);
else
System.out.println(" Not Equal”);
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
ob1.equals(ob2));
ob1.equals(ob3));
}
}
12
Returning Object
class Test {
int a ,b;
Test() {
a = 0;
b=0;
}
Test(int i ,int j) {
a = i;
b=j;
}
Test add()
{
Test temp = new Test();
temp.a=a+10;
temp.b=b+10;
return temp;
}}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2 ,4);
Test ob2;
ob2 = ob1.add();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob1.b: " + ob1.b);
System.out.println("After Addition :");
System.out.println("ob2.a: " + ob2.a);
System.out.println("ob2.b: " + ob2.b);
}
}
13
static Members
 Normally a class member must be accessed only with an
object.
 When a member is declared static, it can be accessed before
any objects of its class are created, and without reference to
any object.
 There can be a static method, static variable and a static block
 When objects of class are declared, no copy of a static
variable is made.
 Instead, all instances of the class share the same static
variable.
 Static methods can only call other static methods
 Static methods must only access static data
 Static block gets executed exactly once, when the class is first
loaded.
14
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block
initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}}
OUTPUT
Static block initialized.
x = 42
a = 3
b = 12
15
 Outside of the class in which they are defined, static methods and
variables can be used independently of any object.
 To call a static method and variable from outside its class, class name is
used .
General form:
classname.method( );
Classname.variable1;
16
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
 output :
a = 42
b = 99
17

More Related Content

PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PDF
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
kakarthik685
 
PPTX
Chapter ii(oop)
Chhom Karath
 
PPTX
unit 2 java.pptx
AshokKumar587867
 
PDF
Java Basics - Part2
Vani Kandhasamy
 
PPTX
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
PPTX
UNIT_-II_2021R.pptx
RDeepa9
 
PPTX
class object.pptx
Killmekhilati
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
kakarthik685
 
Chapter ii(oop)
Chhom Karath
 
unit 2 java.pptx
AshokKumar587867
 
Java Basics - Part2
Vani Kandhasamy
 
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
UNIT_-II_2021R.pptx
RDeepa9
 
class object.pptx
Killmekhilati
 

Similar to Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf (20)

PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
PPTX
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
PPTX
JAVA Module 2 ppt on classes and objects and along with examples
Praveen898049
 
PPT
5.CLASSES.ppt(MB)2022.ppt .
happycocoman
 
PPTX
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
PPTX
Mpl 9 oop
AHHAAH
 
PPTX
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
PPTX
Chap2 class,objects contd
raksharao
 
PPT
Object and class
mohit tripathi
 
PPTX
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
PPTX
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
PPTX
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
PPT
Class & Object - User Defined Method
PRN USM
 
PPT
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
DOCX
Lecture11.docx
ASADAHMAD811380
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
PPTX
Class and Object.pptx from nit patna ece department
om2348023vats
 
PPTX
Lab4-Software-Construction-BSSE5.pptx ppt
MuhammadAbubakar114879
 
PPTX
Lecture 5
talha ijaz
 
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
JAVA Module 2 ppt on classes and objects and along with examples
Praveen898049
 
5.CLASSES.ppt(MB)2022.ppt .
happycocoman
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Mpl 9 oop
AHHAAH
 
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
Chap2 class,objects contd
raksharao
 
Object and class
mohit tripathi
 
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
Class & Object - User Defined Method
PRN USM
 
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Lecture11.docx
ASADAHMAD811380
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Class and Object.pptx from nit patna ece department
om2348023vats
 
Lab4-Software-Construction-BSSE5.pptx ppt
MuhammadAbubakar114879
 
Lecture 5
talha ijaz
 
Ad

Recently uploaded (20)

PDF
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
PDF
5 Influence line.pdf for structural engineers
Endalkazene
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PDF
6th International Conference on Artificial Intelligence and Machine Learning ...
gerogepatton
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPTX
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
demidovs1
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
Simulation of electric circuit laws using tinkercad.pptx
VidhyaH3
 
Activated Carbon for Water and Wastewater Treatment_ Integration of Adsorptio...
EmilianoRodriguezTll
 
5 Influence line.pdf for structural engineers
Endalkazene
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
6th International Conference on Artificial Intelligence and Machine Learning ...
gerogepatton
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
Ppt for engineering students application on field effect
lakshmi.ec
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Edge to Cloud Protocol HTTP WEBSOCKET MQTT-SN MQTT.pptx
dhanashri894551
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
demidovs1
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Simulation of electric circuit laws using tinkercad.pptx
VidhyaH3
 
Ad

Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf

  • 2. Constructors  Java allows objects to initialize themselves when they are created through the use of a constructor.  Constructors play the role of initializing objects  Constructors are a special kind of methods that are invoked using the new operator when an object is created.
  • 3. Constructors, cont.  Constructors have following properties:  Constructors must have the same name as the class itself.  Constructors do not have a return type— not even void.  The implicit return type is class itself  A constructor with no parameters is referred to as a default constructor and constructor with parameters is called as parameterized constructor 3
  • 4. Program for constructor class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo1 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); //constructor invoked Box mybox2 = new Box(); //constructor invoked double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 4
  • 5. Parameterized Constructors class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo2 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 5
  • 6. Exercise  WAP to create class rectangle and calculate area and perimeter of it by using constructor.  WAP to create class Employee. Add methods to read and display employee information by using constructor such as id and salary. 6
  • 7. Method Overloading  Two or more methods within the same class that have the same name but methods must differ in the type and/or number of their parameters.  Method overloading is one of the ways that Java implements polymorphism  When an overloaded method is invoked, Java uses the type and/or number of arguments to determine which version of the overloaded method to actually call. 7
  • 8. Example class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.2); System.out.println("Result of ob.test(123.2): " + result); } } 8
  • 9. Constructor Overloading  Similar to method overloading we can also overload constructor .  Overloaded constructors have the same name but must differ in the type and/or number of their parameters. 9
  • 10. Example class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } } 10
  • 11. Exercise  WAP to overload add method to perform addition of two integers, addition of three integers and addition of two float numbers.  WAP to create overloaded constructor to calculate area of triangle ,rectangle and circle. 11
  • 12. Using Objects as Parameters class Test { int a, b; Test(int i, int j) { a = i; b = j; } void add(Test o) { if(o.a == a && o.b == b) System.out.println(" Equal”); else System.out.println(" Not Equal”); } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); ob1.equals(ob2)); ob1.equals(ob3)); } } 12
  • 13. Returning Object class Test { int a ,b; Test() { a = 0; b=0; } Test(int i ,int j) { a = i; b=j; } Test add() { Test temp = new Test(); temp.a=a+10; temp.b=b+10; return temp; }} class RetOb { public static void main(String args[]) { Test ob1 = new Test(2 ,4); Test ob2; ob2 = ob1.add(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob1.b: " + ob1.b); System.out.println("After Addition :"); System.out.println("ob2.a: " + ob2.a); System.out.println("ob2.b: " + ob2.b); } } 13
  • 14. static Members  Normally a class member must be accessed only with an object.  When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.  There can be a static method, static variable and a static block  When objects of class are declared, no copy of a static variable is made.  Instead, all instances of the class share the same static variable.  Static methods can only call other static methods  Static methods must only access static data  Static block gets executed exactly once, when the class is first loaded. 14
  • 15. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); }} OUTPUT Static block initialized. x = 42 a = 3 b = 12 15
  • 16.  Outside of the class in which they are defined, static methods and variables can be used independently of any object.  To call a static method and variable from outside its class, class name is used . General form: classname.method( ); Classname.variable1; 16
  • 17. class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } }  output : a = 42 b = 99 17