0% found this document useful (0 votes)
8 views22 pages

Lecture9 - ICT102 - T222 For Lecture Class

lect

Uploaded by

priyanshumonga5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views22 pages

Lecture9 - ICT102 - T222 For Lecture Class

lect

Uploaded by

priyanshumonga5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

ICT102

Introduction to Programming
Lecture 9 – Class Constructors and Methods Overloading
Focus for this week

01 Constructors, this Operator

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.

– Constructors have the same name as the class.


– Constructors have no return type (not even void).
– Constructors may not return any values.
– Constructors are typically public.
6-5

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

The Default Constructor


• When an object is created, its constructor is
always called.
• If you do not write a constructor, Java provides
one when the class is compiled. The constructor
that Java provides is known as the default
constructor.
– It sets all of the object’s numeric fields to 0.
– It sets all of the object’s boolean fields to false.
– It sets all of the object’s reference variables to the
special value null.
6-8

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

The String Class Constructor


• One of the String class constructors accepts a string literal as an argument.

• This string literal is used to initialize a String object.

• For instance:

String name = new String("Michael Long");

String name = “Michael Long”;


6-10

The String Class Constructor


• This creates a new reference variable name that
points to a String object that represents the
name “Michael Long”
• Because they are used so often, String objects
can be created with a shorthand:

String name = "Michael Long";


6-11

Overloading Methods and Constructors


• Two or more methods in a class may have the same name as long as their parameter
lists are different.

• 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

Overloaded Method add


public int add(int num1, int num2)
{
int sum = num1 + num2; // local variables
return sum; // returning an int value
}

public String add (String str1, String str2)


{
String combined = str1 + str2; // local variables
return combined; } // returning a string value
6-13

Method Signature and Binding


• A method signature consists of the method’s name and the
data types of the method’s parameters, in the order that
they appear. The return type is not part of the signature.

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); }

// Driver or test code


public static void main(String args[]){
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
6-15

Rectangle Class Constructor Overload


If we were to add the no-arg constructor we wrote
previously to our Rectangle class in addition to
the original constructor we wrote, what would
happen when we execute the following calls?

Rectangle box1 = new Rectangle();


Rectangle box2 = new Rectangle(5.0, 10.0);
6-16

Rectangle Class Constructor Overload


If we were to add the no-arg constructor we wrote
previously to our Rectangle class in addition to
the original constructor we wrote, what would
happen when we execute the following calls?

Rectangle box1 = new Rectangle();


Rectangle box2 = new Rectangle(5.0, 10.0);

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

The BankAccount Example


BankAccount.java BankAccount
AccountTest.java -balance:double

+BankAccount()

Overloaded Constructors +BankAccount(startBalance:double)


+BankAccount(strString):
+deposit(amount:double):void
Overloaded deposit methods
+deposit(str:String):void
+withdraw(amount:double):void
Overloaded withdraw methods
+withdraw(str:String):void
+setBalance(b:double):void
Overloaded setBalance methods
+setBalance(str:String):void
+getBalance():double
6-18

Packages and import Statements


• Classes in the Java API are organized into
packages.
• Explicit and Wildcard import statements
– Explicit imports name a specific class
 import java.util.Scanner;
– Wildcard imports name a package, followed by an *
 import java.util.*;

• The java.lang package is automatically made


available to any Java class.
6-19

Some Java Standard Packages


8-20

Passing Objects as Arguments


Examples:
PassObject.java A Rectangle object
PassObject2.java length: 12.0
width: 5.0
displayRectangle(box);

Address

public static void displayRectangle(Rectangle r)


{
// Display the length and width.
System.out.println("Length: " + r.getLength() +
" Width: " + r.getWidth());
}
8-21

Returning Objects From Methods


• Methods are not limited to returning the primitive data
types.
• Methods can return references to objects as well.
• Just as with passing arguments, a copy of the object is
not returned, only its address.
• See example: ReturnObject.java
• Method return type:

public static BankAccount getAccount()


{

return new BankAccount(balance);
}
6-22

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.

You might also like