Lecture9 - ICT102 - T222 For Lecture Class
Lecture9 - ICT102 - T222 For Lecture Class
Introduction to Programming
Lecture 9 – Class Constructors and Methods Overloading
Focus for this week
02 Methods Overloading
6-3
Constructors
• Classes can have special methods called
constructors.
• A constructor is a method that is automatically
called when an object is created.
• Constructors are used to perform operations at
the time an object is created.
• Constructors typically initialize instance fields and
perform other object initialization tasks.
6-4
Constructors
• Constructors have a few special properties that set them
apart from normal methods.
Lets Practice
Constructor for Rectangle Class
/**
Constructor
@param len The length of the rectangle.
@param w The width of the rectangle.
*/
public Rectangle(double len, double w)
{
length = len;
width = w;
}
6-6
Constructors in UML
• In UML, the most common way constructors are defined is:
Rectangle
Notice there is no
return type listed
- width : double for constructors.
- length : double
+Rectangle(len:double, w:double)
+ setWidth(w : double) : void
+ setLength(len : double): void
+ getWidth() : double
+ getLength() : double
+ getArea() : double
6-7
Lets Practice
Writing Your Own No-Arg Constructor
• A constructor that does not accept arguments is
known as a no-arg constructor.
• The default constructor (provided by Java) is a no-
arg constructor.
• We can write our own no-arg constructor
public Rectangle()
{
length = 1.0;
width = 1.0;
}
6-9
• For instance:
• When this occurs, it is called method overloading. This also applies to constructors.
• Method overloading is important because sometimes you need several different ways to
perform the same operation.
6-12
add(int, int)
Signatures of the
add methods of
add(String, String)
previous slide
• The process of matching a method call with the correct
method is known as binding. The compiler uses the
method signature to determine which version of the
overloaded method to bind the call to.
6-14
Lets Practice
// Overloaded spublic class Sum{
um(). This sum takes two int parameters
public int sum(int x, int y){
return (x + y); }
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z){
return (x + y + z); }
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y){
return (x + y); }
The first call would use the no-arg constructor and box1
would have a length of 1.0 and width of 1.0.
The second call would use the original constructor and box2
would have a length of 5.0 and a width of 10.0.
6-17
+BankAccount()
Address
Check Point
public class Book
{
// instance variables or attributes
private String title;
private String author;
private String publisher;
private int copiesSold;
}
-write a constructor for the class. The constructor should
accept an argument for each of the fields.