lect02-part2-week2
lect02-part2-week2
Lecture 2
(Cont.)
1
Constructors…..
Constructor must have the same name as the class name.
Constructors do not have a return type—not even void, can not be static.
default blank constructor, is provided automatically only if no constructors are explicitly
declared in the class.
A constructor is generally used to do initial setup for an object
class Circle {
double radius=0 ;
public Circle()
{
}
public Circle (double r)
{
radius=r;
}
public double findArea()
{
//
}
}
multiple constructors with the same name but different signatures can
exist.(overloading)
2
How to create an object from class?
To construct an object from a class, invoke a constructor of the class using the new
operator, as follows: new ClassName(arguments);
constructor can contain any type of code that a normal method could contain. When
constructor is invoked an object is created and also code in constructor is executed.
bike1 bike2
: Bicycle : Bicycle
bike1 = new Bicycle( );
bike1.setOwnerName ("Adam
Smith"); ownerName ownerName
“Adam Smith” “Ben Jones”
bike2 = new Bicycle( );
bike2.setOwnerName ("Ben Jones" );
Sample Code
Chapter 4 -6
Example :Adding constructors to class Radio
public class Radio{
int volume; public void turnOn(){
String station; powerStatus=true;
boolean powerStatus; }
public Radio() public void turnOff(){
{ volume=0;
volume=3; powerStatus=false;
} }
public Radio(int startVolume) }
{
volume= startVolume;
class Test
}
{
public void increaseVolume(){
public static void main (String [] args)
volume++;
{
}
Radio radio1=new Radio();
public void decreaseVolume(){
radio1.turnOn();
volume--;
radio1.increaseVolume();
}
Radio radio2=new Radio(5);
public void changeStation(String newStation){
}
station=newStation;}
}
7
What will be the output ?
Page 1 Page 2
Arguments and Parameters
class Sample { class Account { parameter
public static void . . .
main(String[] arg) {
Account acct = new Account(); public void add(double amt) {
. . .
balance = balance + amt;
acct.add(400); }
. . . . . .
}
}
. . . argument
}
class Box{
double width;
double height;
double depth;
Box(double w, double h, double d){
width = w;
height = h;
depth = d;
}
Box() ▪this is used to call a constructor from another
{ constructor.
width = 1; ▪call to this must be first statement in constructor
height = 1; otherwise compile error
depth = 1;
}
Box(double y)
{
this(y,y,y);
}
}
12
Information Hiding and Visibility Modifiers
Client Service
Chapter 4 - 14
Data Members Should Be private
class Bicycle
{ Class variable
Instance Variables Class Variables int speed;
(Non-static Fields) (static Fields) static int numberOfBicycles;
void speedUp(int increment)
Instance Variables {
speed += increment; parameter
}
void caluclateDistance(String S)
Local Variables
{
int x;
…………………………
}
static void m(){….}
}
16
Methods
class Bicycle
{
int speed;
static int numberOfBicycles;
void speedUp(int increment)
{
Instance method
speed += increment;
}
static void m()
{
….
Class method
}
}
17
Members of a class
18
Variables Initialization
Member variables that are declared but not initialized will be set to a default by the compiler
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object refrence) null
boolean false
local variables :that are declared but not initialized will not be set to a default by the compiler
Accessing an uninitialized local variable will result in a compile-time error
19
Accessing an Object's instance variables and Methods
class Test {
public static void main (String [] arg)
class A {
{ A a1=new A();
public int x; a1.x=7;
public int y; a1.m1();
public void m1(){ A a2=new A();
y=9; a2.x=10;
m2();
} }
public void m2(){ }
}
} x=7 x=10
a1,a2 are of reference data type y=9 y=0
a1 a2
Rules :
Instance variable of object are accessed from another class by :objectName.variableName
instance methods are accessed from another class by :objectName.methodName(argument)
Inside same class , members can be called with their names only
20
Example :Accessing members of class Circle
Class BankAccount
public class BankAccount
{
int accountNum=0;
float accountBalance=0;
Class Bank
public BankAccount( ) {} public class Bank
public BankAccount(int accountNumber, float balance)
{
{
this.accountNum=accountNumber; public static void main (String [] arg)
this.accountBalance=balance; {
}
BankAccount account1=new BankAccount();
void setAccountNumber(int num)
{ account1.setAccountNumber(456);
this.accountNum = num; account1.deposit(1000);
} BankAccount account2=new BankAccount(590,200);
void withdraw(float amount)
{
}
this.accountBalance = this.accountBalance -amount; }
}
void deposit (float amount)
{
this. accountBalance = this. accountBalance + amount;
}
}
22
Calling Methods of the Same Class
• So far, we have been calling a method of another class (object).
• It is possible to call method of a class from another method of
the same class.
– in this case, we simply refer to a method without dot notation
Chapter 4 - 23
Instance Variable Hiding
when a local variable has the same name as an instance variable, the local variable
hides the instance variable.
class A{ class A
int i=20; {
int j=10; int i=20;
void m() int j=10;
{ void m()
int i=5; {
System.out.println("i="+i); //prints 5 int i=5;
} System.out.println("i="+this.i); //prints 20
} }
}
class Test
{
public static void main(String [] arg)
{
A a=new A();
a.m();
}
24
The this Keyword
• this is always a reference to current object, you must use this to overcome local variable hiding
26
Example
class A{
static int x;
int y;
x 1 }
3
2
y=0
y=1 class Test
{
public static void main (String [] arg)
a1 {
y=2
y=0
A.x++;
A a1=new A();
a2 a1.x++;
a1.y++;
A a2=new A();
a2.x++;
a2.y++;
a2.y++;
}
}
27
Static Class members :Static methods
class Student{
static String deanName;
Static methods String name;
int registrationNumber;
Ex: static void m(){} Student( String studentName , int regNumber){
Can be called without creation of any object
Can only access static variables and only call name=studentName;
static methods. registrationNumber=regNumber;
Can be called in same class by methodName() }
or classname.methodName() public static void setDeanName(String name)
or ObjectName.methodName() {
(same effect) deanName=name;
Can be called in another class by }
classname.methodName() or
}
ObjectName.methodName()
(same effect)
class Test{
public static void main (String [] arg){
Student student1=new Student("Ahmed Aly",
123);
Student student2=new Student("Akram
access modifiers and static keyword can ahmed", 367);
appear in any order Student.setDeanName("Dr Mohamed");
28
}}