[go: up one dir, main page]

0% found this document useful (0 votes)
7 views28 pages

lect02-part2-week2

The document provides an overview of constructors in Java, including their characteristics, usage, and examples of creating objects from classes. It also discusses the Bicycle and Radio classes, demonstrating how to use constructors and methods, as well as the concept of information hiding through access modifiers. Additionally, it covers the importance of static and instance members, variable initialization, and calling methods within the same class.
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)
7 views28 pages

lect02-part2-week2

The document provides an overview of constructors in Java, including their characteristics, usage, and examples of creating objects from classes. It also discusses the Bicycle and Radio classes, demonstrating how to use constructors and methods, as well as the concept of information hiding through access modifiers. Additionally, it covers the importance of static and instance members, variable initialization, and calling methods within the same class.
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/ 28

Programming2(CS272)

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.

class Circle { class Test{


double radius=0 ; public static void main (String [] arg)
public Circle()
{ {
Circle c1;
}
public Circle (double r) c1=new Circle();
{ Circle c2= new Circle();
radius=r;
} Circle c3= new Circle(5.1);
public double findArea() }
{
return radius * radius * 3.14;
}
}
}
c1,c2,c3 are reference data types
c1 radius=0 c2 radius=0 c3 radius=5.1
3
Revisiting the Bicycle Class
class Bicycle {
// Data Member
private String ownerName;
//Constructor: Initialzes the data member
public Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName ( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName (String name ) {
ownerName = name;
}
}
Using the Bicycle Class
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;

bike1 = new Bicycle( ); //Create and assign values to bike1


bike1.setOwnerName ("Adam Smith" );

bike2 = new Bicycle( ); //Create and assign values to bike2


bike2.setOwnerName ("Ben Jones" );

owner1 = bike1.getOwnerName ( ); //Output the information


owner2 = bike2.getOwnerName ( );

System.out.println (owner1 + " owns a bicycle." );


System.out.println (owner2 + " also owns a bicycle." );
}
}
Multiple Instances
• Once the Bicycle class is defined, we can create multiple instances.

bike1 bike2

Bicycle 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 ?

public class Box


{
double width; 1-compile error
double height; 2-Runtime error
double depth;
double volume;
3-Compile and run without error
public Box(double w,double h,double d)
{
width=w;
height=h;
1-compile error
depth=d;
} Default constructor should be written
}

public class Test {


public static void main(String args[]) {
Box mybox1 = new Box( );
}
8
Example :The Account Class
class Account {
private String ownerName; public void setInitialBalance
(double bal) {
private double balance;
balance = bal;
public Account( ) { }
ownerName = "Unassigned";
balance = 0.0; public void setOwnerName
} (String name) {
public void add(double amt) { ownerName = name;
balance = balance + amt; }
} }
public void deduct(double amt) {
balance = balance - amt;
}
public double getCurrentBalance( ) {
return balance;
}
public String getOwnerName( ) {
return ownerName;
}

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
}

• An argument is a value we pass to a method


• A parameter is a placeholder in the called method
to hold the value of the passed argument.
Matching Arguments and Parameters
• The number or
arguments and the
Demo demo = new Demo( );
parameters must be the
int i = 5; int k = 14; same
demo.compute(i, k, 20);
3 arguments
• Arguments and
Passing Side parameters are
paired left to right

class Demo { • The matched pair


public void compute(int i, int j, double x) { must be
. . .
}
3 parameters assignment-compatibl
}
e (e.g. you cannot
pass a double
Receiving Side argument to a int
parameter)

©The McGraw-Hill Companies, Inc.


Permission required for reproduction or display. Chapter 4 - 11
Calling a constructor from another constructor

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

• The modifiers public and private designate the


accessibility of data members and methods.
• If a class component (data member or method) is
declared private, client classes cannot access it.
• If a class component is declared public, client
classes can access it.
• Internal details of a class are declared private and
hidden from the clients. This is information
hiding.
Accessibility Example
… class Service {
public int memberOne;
Service obj = new Service();
private int memberTwo;
obj.memberOne = 10;
public void doOne() {

obj.memberTwo = 20;
}
private void doTwo() {
obj.doOne();

obj.doTwo(); }
}

Client Service

Chapter 4 - 14
Data Members Should Be private

• Data members are the implementation details


of the class, so they should be invisible to the
clients. Declare them private .
• Exception: Constants can (should) be declared
public if they are meant to be used directly by
the outside methods.
Variables

Member Variables Local Variables Parameters


storing the state of the object Variables in a method Variables in method declaration
Defined outside methods

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

Instance Methods Class Methods


(Non-static methods) (static 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

Static Members Non Static Members

Static Static Non Static Non Static


variables methods variables methods

18
Variables Initialization
Member variables that are declared but not initialized will be set to a default by the compiler

Data Type Default Value


byte 0
short 0
int 0

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 Circle{ class Test {


public int radius; public static void main (String [] arg)
public double area; {
public void setArea() Circle c1=new Circle();
{ c1.radius=5;
this.area=3.14*(this.radius)*(this.radius); c1.setArea();
//area=3.14*radius*radius;
System.out.println(c1.area);
} Circle c2=new Circle(8);
Circle() c2.setArea();
{ System.out.println(c2.area);
} }
Circle(int r){ }
this.radius=r;
//radius=r;} radius=5 radius=8
} area=3.14*8*8
area=3.14*5*5
c1 c2
Rule :
Instance variables in instance methods are always related to the calling object, JAVA add
this. before each of them implicitly . You can omit writing “this”
As a rule, constructors with fewer arguments should call those with more
21
Example :Accessing members of class BankAccount

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

A redundant use of this. A mandatory use of this.


class Box{ class Box{
double width ; double width ;
double height ; double height ;
double depth ; double depth ;
int i;
Box(double w, double h, double d) Box(double width , double height, double depth) {
{ this.width = width;
this.width = w; this.height = height;
this.height = h; this.depth = depth;
this.depth = d; }
} //overcome instance variable hiding
void m1(){
void incrementWidth() int i=7;
{ this.i=10;
this.width++; }
} void m(double width){
} this.width=width;
25
}}
Static Class members: Static variables
class Student{
Static variables (class Variables)
static String dean;
Ex: static int x; String name;
int registrationNumber;
Only one copy of this variable exist, all Student( String studentName , int regNumber)
objects share the same copy with the
same value.
{
name=studentName;
Can be accessed without creation of any
object. registrationNumber=regNumber;
Can be accessed in same class by
}
variableName or classname.varaibleName }
or ObjectName.variableName.
Can be accessed in another class by class Test{
classname.varaibleName or public static void main (String [] arg)
ObjectName.variableName. {
Student student1=new Student("Ahmed Aly", 123);
Student student2=new Student("Akram ahmed", 367);
Student.dean="Dr Mohamed";
Local Variables can never be declared System.out.println(student1.dean);
static. System.out.println(student2.dean);
}}

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

You might also like