Introduction To Java Programming - Constructor
Introduction To Java Programming - Constructor
Objectives
Able to define constructor
Able to declare constructor
Able to create overloading
constructor
Purpose and Function of
Constructor
Constructors have one purpose in life: to
create an instance of a class. This can
also be called creating an object, as in:
}
}
Output
The following will be display if
you compile and run the
program.
Example3: Declaring
Constructor
public class Transportation
{
String name;
int year;
String model;
}
}
Example3: Declaring
Constructor
The following will be displayed if
you compile and run the
program.
Check Point
Class Bicycle has 3 data members as String id,
String ownerName and int yearBuilt.
Create a constructor without parameter (default
constructor) that will assigned a default value of
“001”,”Malek” and 2006 when an instance of Bike1 is
created.
Create a constructor with parameter that will pass
default value of “001”,”Malek” and 2006 when an
instance of Bike1 is created through parameter.
Create the test class too !. Compile and execute in your
virtual compiler
Write your answer…
Overloaded Constructor
Constructor has exactly the same name
as the defining class.
}
Example4: Overloaded
Constructor
public class TestNumber
{
public static void main (String[ ] args)
{
public V ( )
public class TestV
{ a = 0.0; {
b = 0.0; public static void main (String[ ]
}
args)
public V ( double m, double n ) {
{ a = m; V x = new V(100.0,
b=n
} 200.0 );
x.updateValues();
public void updateValues()
{ a = a + 5;
x.display();
b = b +10; V y = new V( );
}