Upload
elle-xevierre-g
View
244
Download
0
Embed Size (px)
Citation preview
8/9/2019 Introduction to Java Programming - Constructor
1/20
ConstructorConstructor
8/9/2019 Introduction to Java Programming - Constructor
2/20
ObjectivesObjectives
Able to define constructorAble to define constructor
Able to declare constructorAble to declare constructor
Able to create overloadingAble to create overloadingconstructorconstructor
8/9/2019 Introduction to Java Programming - Constructor
3/20
Purpose and Function ofPurpose and Function of
ConstructorConstructor Constructors have one purpose in life: toConstructors have one purpose in life: to
create an instance of a class. This cancreate an instance of a class. This canalso be called creating an object, as in:also be called creating an object, as in:
University unikl = new University();University unikl = new University();
The purpose of methods, by contrast, isThe purpose of methods, by contrast, ismuch more general.much more general.
A method's basic function isA method's basic function is to executeto executeJava codes.Java codes.
8/9/2019 Introduction to Java Programming - Constructor
4/20
Signature differencesSignature differences
Constructors and methods differ in three aspects of theConstructors and methods differ in three aspects of thesignature: modifiers, return type, and name.signature: modifiers, return type, and name.
Like methods, constructors can have any of the accessLike methods, constructors can have any of the access
modifiers: public, protected, private, or none (oftenmodifiers: public, protected, private, or none (oftencalledcalled packagepackage oror friendlyfriendly). Unlike methods,). Unlike methods,constructors can take only public access modifiers.constructors can take only public access modifiers.
Therefore, constructorsTherefore, constructors cannot be final or static.cannot be final or static.
The return types are very different too. Methods canThe return types are very different too. Methods canhave any valid return type, or no return type, in whichhave any valid return type, or no return type, in whichcase the return type is given as void. Constructors havecase the return type is given as void. Constructors haveNONO return type, not even void.return type, not even void.
8/9/2019 Introduction to Java Programming - Constructor
5/20
Signature differencesSignature differences
Finally, in terms of the signature, methods andFinally, in terms of the signature, methods andconstructors have different names.constructors have different names.
Constructors have the same name as theirConstructors have the same name as their
class; by convention, methods use namesclass; by convention, methods use namesother than the class name.other than the class name.
If the Java program follows normalIf the Java program follows normalconventions, methods will start with aconventions, methods will start with alowercase letter, constructors with anlowercase letter, constructors with anuppercase letter. Also, constructor names areuppercase letter. Also, constructor names areusually nouns because class names are usuallyusually nouns because class names are usuallynouns; method names usually indicate actions.nouns; method names usually indicate actions.
8/9/2019 Introduction to Java Programming - Constructor
6/20
Example1: DeclaringExample1: Declaring
ConstructorConstructorpublic class Universitypublic class University{{
private String institute;private String institute;
publicpublicUniversity (String input)University (String input)
{{ institute = input;institute = input;}}
}}
public class UniversityTestpublic class UniversityTest
{{ public static void main(String args[ ])public static void main(String args[ ])
{{University unikl = new University (miit");University unikl = new University (miit");
}}
}}
Constructor name
Receiving parameter
Store value of input into name
l l i
8/9/2019 Introduction to Java Programming - Constructor
7/20
Example2: DeclaringExample2: Declaring
ConstructorConstructorpublic class Transportationpublic class Transportation
{{private String name;private String name;
private int year;private int year;
private String model;private String model;
public Transportation( )public Transportation( )
{{name = Pesona";name = Pesona";
year = 2007;year = 2007;
model = Sedan1.4";model = Sedan1.4";
}}
public void DisplayInfo( )public void DisplayInfo( ){{
System.out.println("The default car name is "+name);System.out.println("The default car name is "+name);
System.out.println("The default car year is "+year);System.out.println("The default car year is "+year);
System.out.println("The default car model is "+model);System.out.println("The default car model is "+model);
}}
}}
Constructor name
No parameter
Store default value into data member
l 2 l i
8/9/2019 Introduction to Java Programming - Constructor
8/20
Example2: DeclaringExample2: Declaring
ConstructorConstructor
public class TransportationTestpublic class TransportationTest
{{
public static void main(String[ ] args)public static void main(String[ ] args){{
Transportation car = new Transportation();Transportation car = new Transportation();
car.DisplayInfo( );car.DisplayInfo( );
}}
}}
Create an instance called car
Call DisplayInfo method
8/9/2019 Introduction to Java Programming - Constructor
9/20
OutputOutput
The following will be display ifThe following will be display if
you compile and run theyou compile and run the
program.program.
8/9/2019 Introduction to Java Programming - Constructor
10/20
Example3: DeclaringExample3: Declaring
ConstructorConstructorpublic class Transportation{
String name;int year;String model;
public Transportation (String CarName, int CarYear, String CarModel)
{name=CarName;year=CarYear;model=CarModel
}
public void DisplayInfo( ){
System.out.println("The default car name is "+name);System.out.println("The default car year is "+year);System.out.println("The default car model is "+model);
}
}
8/9/2019 Introduction to Java Programming - Constructor
11/20
Example3: DeclaringExample3: Declaring
ConstructorConstructorpublic class TransportationTestpublic class TransportationTest
{{
public static void main(String[ ] args)public static void main(String[ ] args)
{{
Transportation car = new Transportation(Perdana,2002,DANA1.6);Transportation car = new Transportation(Perdana,2002,DANA1.6);
car.DisplayInfo( );car.DisplayInfo( );
}}
}}
8/9/2019 Introduction to Java Programming - Constructor
12/20
Example3: DeclaringExample3: Declaring
ConstructorConstructorThe following will be displayed ifThe following will be displayed if
you compile and run theyou compile and run the
program.program.
8/9/2019 Introduction to Java Programming - Constructor
13/20
Check PointCheck Point
Class Bicycle has 3 data members as String id,Class Bicycle has 3 data members as String id,
String ownerName and int yearBuilt.String ownerName and int yearBuilt. Create aCreate a constructor without parameterconstructor without parameter (default(default
constructor) that will assigned a default value ofconstructor) that will assigned a default value of
001,Malek and 2006 when an instance of Bike1 is001,Malek and 2006 when an instance of Bike1 iscreated.created.
Create aCreate a constructor with parameterconstructor with parameter that will passthat will pass
default value of 001,Malek and 2006 when andefault value of 001,Malek and 2006 when an
instance of Bike1 is created through parameter.instance of Bike1 is created through parameter.
Create the test class too !. Compile and execute in yourCreate the test class too !. Compile and execute in yourvirtual compilervirtual compiler
8/9/2019 Introduction to Java Programming - Constructor
14/20
Write your answerWrite your answer
8/9/2019 Introduction to Java Programming - Constructor
15/20
Overloaded ConstructorOverloaded Constructor
Constructor has exactly the same nameConstructor has exactly the same nameas the defining class.as the defining class.
Therefore, if you provide two or moreTherefore, if you provide two or moreconstructors for the same class, theyconstructors for the same class, theyare overloaded by definition.are overloaded by definition.
Those overloaded constructors used inThose overloaded constructors used inthe same program MUST have differentthe same program MUST have differentargument lists so that compiler canargument lists so that compiler can
differentiate them.differentiate them.
8/9/2019 Introduction to Java Programming - Constructor
16/20
Example4: OverloadedExample4: Overloaded
ConstructorConstructorpublic classpublic class NumberNumber
{{ private doubleprivate double aa;;
private Stringprivate String bb;;
public Number ( )public Number ( ) // default constructor// default constructor
{{ aa = 0.0;= 0.0; bb = Hello;= Hello;
}}
public Number ( double m, String n )public Number ( double m, String n ) // constructor// constructor
with 2 argumentswith 2 arguments{{ aa == mm;;
bb == nn;;
}}
}}
8/9/2019 Introduction to Java Programming - Constructor
17/20
Example4: OverloadedExample4: Overloaded
ConstructorConstructorpublic classpublic class TestNumberTestNumber
{{
public static void main (String[ ] args)public static void main (String[ ] args)
{{
NumberNumber myObj1 =myObj1 = newnew NumberNumber (100.0,Welcome );(100.0,Welcome );
////call constructor with argumentscall constructor with arguments
NumberNumber myObj2myObj2 = new= new NumberNumber( );( ); // call default// call default
constructorconstructor}}
}} // end class// end class TestNumberTestNumber
8/9/2019 Introduction to Java Programming - Constructor
18/20
::Check point::::Check point::public classpublic class VV
{ private double{ private double
aa
;;
private doubleprivate double bb;;
public V ( )public V ( ){{ aa = 0.0;= 0.0;
bb = 0.0;= 0.0;
}}
public V ( double m, double n )public V ( double m, double n )
{{ aa == mm;;
bb == nn
}}
public void updateValues()public void updateValues()
{ a = a + 5;{ a = a + 5;
b = b +10;b = b +10;
}}
public void display( )public void display( )
{{
System.out.println( a + b );System.out.println( a + b );
System.out.println( b - a );System.out.println( b - a );
}}
}} // end class V// end class V
public class TestVpublic class TestV
{{
public static void main (String[ ]public static void main (String[ ]
args)args)
{{ VV xx = new V(100.0,= new V(100.0,
200.0 );200.0 );xx.updateValues();.updateValues();
xx.display();.display();
VV yy = new V( );= new V( );
yy.updateValues();.updateValues();
yy. display( );. display( );
}}
}} // end class TestV// end class TestV
What is the output for the above prograWhat is the output for the above progra
8/9/2019 Introduction to Java Programming - Constructor
19/20
ExerciseExerciseCreate a class ShortCourse. ShortCourse class has 4 private dataCreate a class ShortCourse. ShortCourse class has 4 private data
members, courseTitle, courseId, courseFee and courseDuration.members, courseTitle, courseId, courseFee and courseDuration.
A public method, updatedFee() will calculate theA public method, updatedFee() will calculate the
new fees of specific courses based on the following discount ratenew fees of specific courses based on the following discount rateshown below:shown below:
courseIdcourseId Discount rateDiscount rate
ICT1010ICT1010 25%25%
ICT1056ICT1056 10%10%
OthersOthers 8%8%
Another public method, displayCourseDetails() will display allAnother public method, displayCourseDetails() will display allinformation about the course.information about the course.
If the new fees is greater than RM100, acknowledge the user thatIf the new fees is greater than RM100, acknowledge the user thatthey will be given a free one-week workshop.they will be given a free one-week workshop.
Create your test class called ShortCourseTest. In this class, write aCreate your test class called ShortCourseTest. In this class, write amain() method and call updatedFee() to calculate new fees andmain() method and call updatedFee() to calculate new fees anddisplay course details by calling displayCourseDetails() .display course details by calling displayCourseDetails() .
You are to produce a program using :You are to produce a program using :
default constructor(coded)default constructor(coded)
constructor with argumentsconstructor with arguments
8/9/2019 Introduction to Java Programming - Constructor
20/20
Extra ReadingExtra Reading
http://java.sun.com/docs/books/tutorihttp://java.sun.com/docs/books/tutori
al/java/javaOO/constructors.htmlal/java/javaOO/constructors.html