M251 Meeting 3 Full

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

M251 Meeting 3:

Objects and Classes

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan

1
Objectives

 To describe, declare, create objects and classes.

 To create objects using constructors.

 To access objects via reference variables.

 To distinguish between instance and static variables and methods.

 Visibility Modifiers

 To define private data fields with appropriate get and set methods.

2
O.O. Programming Concepts

 The state (attributes)


 The behavior (methods).

3
Classes

Class uses attributes and methods .


Class provides constructors.

4
Example
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Zero-argument-Construct */
Circle() {
}
Constructors
/** One-argument Construct */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}//end of a class
5
6
Constructors
Constructors are a special kind of methods that are
invoked to initialise objects.
//Zero-argument constructor
Circle() {
}

//One-argument constructor
Circle(double newRadius) {
radius = newRadius;
}

7
.Constructors, cont

A constructor with no parameters is referred to as a


no-arg or zero-arg constructor.
Constructors must have the same name as the class itself.
Constructors do not have a return type—not even void.
Constructors are invoked using the new operator.

8
Default Constructor
A class may be defined without constructors. In this
case, a no-arg constructor with an empty body is
implicitly defined in the class.
This constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly defined in the class.
‫اذا ال يوجد قيم مبدئية لمتغيرات الكالس حاضرة في ذهنك في كل‬
‫مرة تقوم فيها بإنشاء اوبجكت من الكالس اترك الكالس بدون اي‬
‫ في هذه الحالة سيقوم الكومبايلر بالنيابة عنك‬constructors
‫ وظيفة هذا الكونستركتور هو‬defualt constructor ‫بإنشاء‬
‫ لالوبجكت الذي يتم‬default values ‫تخصيص قيم ابتدائية‬ 9

‫انشاؤه‬
Declaring Object Reference
Variables

Circle myCircle; //Declare

mycircle = new Circle(); //Create

10
Declaring/Creating Objects
in a Single line

//Declare and Create in a single line


Circle myCircle = new Circle();

11
Data fields (Attributes)
The data fields can be primitive or reference .

Example:

public class Student {

String name; // name has default value null

int age; // age has default value 0

boolean isScienceMajor; // isScienceMajor has default value false

char gender; // c has default value '\u0000'


}

12
‫‪Attributes‬‬
‫شريحة اضافية غير موجودة بالساليدات االساسية‬
The null Value

If a data field of a reference type does not


reference any object, the data field holds a
special literal value, null.

In the previous slide the name reference is an example for a reference

data type field and it does not reference any object so it holds null.
14
Default Value for a Data Field

The default value of a data field is:


null for a reference type,

0 for a numeric type,

false for a boolean type,

and '\u0000' for a char type.

Note: no default value to a local variable.

15
Creating Objects from student Class

public class Test {

public static void main(String[] args) {

Student student = new Student();

System.out.println("name? " + student.name);

System.out.println("age? " + student.age);

System.out.println("isScienceMajor? " + student.isScienceMajor);

System.out.println("gender? " + student.gender);


}

}// End of class

16
Example

Java assigns default values for attributes. But NO


default value to local variables.
‫ قبل محاولة استخدامه‬local ‫يجب تخصيص قيمة لمتغير‬
public class Test {

public static void main(String[] args) {

int x; // x has no default value ‫متغير لوكال‬

String y; // y has no default value ‫متغير لوكال‬

System.out.println("x is " + x); ‫تم استخدامه قبل تخصيص قيمة له‬

System.out.println("y is " + y); ‫تم استخدامع قبل تخصيص قيمة له‬

}
Compile error: variable not initialized 17
Data fields and Methods
Data fields can be classified into:

Instance variables and static variables

Methods can be classified into:

Instance methods and static methods

18
Instance Variables and Instance
Methods
 Instance variables belong to a specific instance
(object). For example:
‫ يجب ان يتم انشاء متغير من الكالس حتى نستطيع الوصول لهذه النوعية من االتربيوت‬

Circle myCircle = new Circle(5.0); : Circle

radius: 5.0
myCircle

 Instance methods are invoked by an instance of the


class. For example:
double x = myCircle.getArea();
‫ يجب ان يتم انشاء متغير من الكالس حتى نستطيع الوصول لهذه النوعية من الميثود‬
Static Variables, Constants,
and Methods
Static variables (class variables) are shared by all the instances of the class.
Class variables are used to keep count of the number of objects of a class type
that have been created. As each object would have to update the count every time
a new object came into existence – (in the constructors).
Static methods (class methods) are not tied to a specific object.
You could not access an instance member from a class method.

Static constants are final variables shared by all the instances of the class,

and usually intiaised upon declaration.

You can access class variables and methods using class name.
20
Static Variable Example
Public class VariableDemo {
‫ستاتيك اتربيوت حيث تم استخدام الكلمة المحجوزة ستاتيك لتعريف المتغير‬
static int count=0;
‫ نتيجة تنفيذ اوبجكت‬count ‫كل اوبجكت جديد يتم انشاؤه سيتعامل مع اخر قيمة وصل اليها المتغير‬
increment ‫سابق للميثود‬
public void increment() { count++; }
public static void main(String args[]) {
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment(); //first count increment
obj2.increment(); //second count increment
System.out.println("Obj1: count is="+obj1.count);//count = 2
System.out.println("Obj2: count is="+obj2.count);//count = 2
}
}
Output:
21
Obj1: count is=2 Obj2: count is=2
Static Constants
static ‫ في حالة ال‬static ‫ مع‬final ‫الحظ ضرورة استخدام كلمة‬
constant

To declare static variables, constants, and


methods, use the static modifier.
For example: PI is declared inside Math class as constant :

So you can access it using: Math.PI


• It is public because we wish it to be available to other classes,
• It is static because it has one value for all objects of the class
• It is final because pi is a constant.
• It is double because that is the most accurate decimal representation we
can use.

22
Scope of Variables

 The scope of instance and static variables is the


entire class.
 The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be initialized explicitly before it can be used.

23
Static methods

Example:

public static double max (double a, double b)


{
if (a>b)
return a;
else
return b;
}

 To access it: double val = Math.max(Math.PI, 4.0);

24
Packages
 A package is used to associate a number of classes.

The .* notation means 'all the classes in the package.

25
‫‪Import package‬‬
‫شريحة اضافية غير موجودة بالساليدات االساسية‬
Access modifiers
There are three keywords associated with controlling levels of access to class members
in Java: public, protected & private. These are known as access modifiers.

There is actually a fourth level of access, 'default'. There is no 'default‘ keyword;


default access arises when none of the access modifiers is specified.

The following example illustrates the accessibility:

Example:

Visibility for a ref. var. defined in Alpha

27
Visibility Modifiers and
Accessor/Mutator Methods

By default, the class, variable, or method can be accessed


by any class in the same package.
 public
The class, data, or method is visible to any class in any package.
 private
The data or methods can be accessed only by the declaring class.
 Protected
The data or methods are accessible inside class where they are declared, and
inside subclasses.
 No modifier: default members can be accessed by all classes in the same
package.

28
The private modifier restricts access to within a class, the default modifier
restricts access to within a package, and the public modifier enables unrestricted
access.

29
The default modifier on a class restricts access to within a package, and the
public modifier enables unrestricted access.

30
NOTE
An object cannot access its private members, as shown
in (b). It is OK, however, if the object is declared in its
own class, as shown in (a).

31
Why Data Fields Should Be private?
To protect data.

To make code easy to maintain.

To achieve encapsulation principle.

32
Getter methods

– A getter method should not change the state of the object.

– All private attributes should have getter methods .

For example, inside the class Circle, we need to add another method:
public double getRadius(){
return radius
}

In the main method: we invoke getRadius() using object name.

33
Setter Method

– It is one that changes the state of an object.


– Setter methods do not normally return a value.

For Example: Inside Circle class we need to add:

Public void setRadius(double r){


radius = r;
}

In the main method: we invoke setRadius() using object name.

34
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObjects(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

CircleWithPrivateDataFields

TestCircleWithPrivateDataFields Run
35
‫الساليدات التالية تحتوي على بعض االسئلة‬
‫مالحظة‪ :‬االسئلة غير مقتبسة من الكويزات السابقة وليس لها اي عالقة بالكويزات‬
‫( فقط لتوضيح بعض االفكار بالميتنج والتأكيد على الفهم )‬

‫‪36‬‬
Exercise: 1
Exercise: 2
Exercise: 3
Exercise: 4
Exercise: 5
Exercise: 6
Exercise: 7
Exercise: 8

What is the instance variable?


Exercise: 9

What is the setter method?


Exercise: 10

How many constructors?


Exercise: 11

What is return type of getArea() method?


Exercise: 12

What is the return type of setRadius() method?


Exercise: 13
Exercise: 14
Exercise: 15
Edited By: Ramadan Ibrahim
Oracle developer OCP certified
Oracle administration OCP certified
CCNA certified
CCNA Security certified
LPI Linux Essential certification (In progress)

You might also like