---
# System prepended metadata

title: Computer Programming II Pre-Lab 2
tags: [Computer Engineering, IUG, Computer Programming II, Pre-Lab]

---

---
title: Computer Programming II Pre-Lab 2
---
<h1 style='border: none'><center>Computer Programming II Pre-Lab 2</center></h1>
<h2 style='border: none'><center>Introduction to Object-Oriented Programming<br>Static & Visibility Modifiers & Encapsulation</center></h2>
<h5><center>The Islamic University of Gaza<br>Engineering Faculty<br>Department of Computer Engineering</center></h5>
<h6>Authors: Usama R. Al Zayan<span style="float:right">2023/02/17</span></h6>

---

## introduction

<p style="text-align:justify">
    In this Pre-lab, we will talk about static variables, constants, and methods. Then explain each visibility modifier. Finally will speak about data field encapsulation and how it prevents direct modifications of data fields.
</p>

## Static Variables and Methods
<p style="text-align:justify">
The data field age in the Person class is known as an instance variable. An instance variable is tied to a specific instance of the class; it is not shared among objects of the same class. For example, suppose that you create the following objects:
</p>

```java=
Person person1 = new Person("Mohammed", "Ahmed", 23, 120200000);
Person person2 = new Person("Osama", "Khaled", 19, 120170000);
```

<p style="text-align:justify">
The age in person1 is independent of the age in person2 and is stored in a 
different memory location. Changes made to person1’s age do not affect 
person2’s age, and vice versa.
</p>
<p style="text-align:justify">
If you want all the instances of a class to share data, use <B>static</B> variables, 
also known as class variables. Static variables store values for the variables 
in a common memory location. Because of this common location, if one 
object changes the value of a static variable, all objects of the same class are 
affected. Java supports static methods as well as static variables. Static 
methods can be called without creating an instance of the class.
</p>

<p style="text-align:justify">
Let’s modify the Person class by adding a static variable counter to count the number of person objects created. When the first object of this class is created, counter is 1. When the second object is created, counter becomes 2. The constructor methods are guaranteed to be invoked once when creating a new object, so we increment the counter in the constructors.
</p>


```java=
class Person {
    // Fields
    String fName;
    String lName;
    int age;
    int ID;
    static int counter = 0; //Static field

    // A Constructor
    public Person() {
        //Increment the counter when creating a new object using first constructor
        counter++; 
    }

    // Another Constructor
    public Person(String fName, String lName, int age, int ID) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        this.ID = ID;
        //Increment the counter when creating a new object using second constructor
        counter++;
    }
}

```

Now the counter field will be incremented when you create any object of class Person. To print the value of counter, get it with the class Name:

```java=
System.out.println(Person.count);
```

You can also define **static** methods. Static methods can be invoked with class name, without creating objects.

<p style="text-align:justify">
An instance method can invoke an instance or static method and access an 
instance or static data field. A static method can invoke a static method and 
access a static data field. However, a static method cannot invoke an 
instance method or access an instance data field, since static methods and 
static data fields do not belong to a particular object. The relationship 
between static and instance members is summarized in the following 
diagram:

</p>

![](https://i.imgur.com/H0iTdml.png)

```java=
// Static Method
public static int getCounter() {
 return counter;
}
```

## Visibility Modifiers
The visibility (access) modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:

* private
* default
* protected
* public

### Private access modifier
<p style="text-align:justify">
The private access modifier is accessible only within class. In the followingexample, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so <span style="color:#e20000" >there is compilation error</span>.
</p>

```java=
class A {
    private int data = 40;
    private void msg() {
        System.out.println("Hello java");
    }
}
public class Simple {
    public static void main(String args[]) {
        A obj = new A();
        System.out.println(obj.data); // Compilation Error
        obj.msg(); // Compilation Error
    }
}
```

### Default access modifier

<p style="text-align:justify">
If you do not use any modifier, it is treated as default by default. The default modifier is accessible only within package. In the following example, we have created two packages pack and mypack. We are accessing the msg() method in obj object, which is an instance of A class from outside its package, since msg() method is not public, so it cannot be accessed from outside the package.
</p>

<h4 style="text-align:center">
    A.java
</h4>

```java=
package pack;
public class A {
    void msg() {
        System.out.println("Hello");
    }
}
```
<h4 style="text-align:center">
    B.java
</h4>

```java=
package mypack;
import pack.A;
public class B {
    public static void main(String args[]) {
        A obj = new A();
        obj.msg();// Compilation Error
    }
}
```

In the above example, the scope of method msg() is default so it cannot be accessed from outside the package.

### Protected access modifier:
Protected access modifier will be explained later, when you start working with inheritance and super classes.
### Public access modifier:
The public access modifier is accessible everywhere. It has the widest scope 
among all other modifiers. Example:


<h4 style="text-align:center">
    A.java
</h4>

```java=
package pack;
public class A {
    public void msg() {
        System.out.println("Hello");
    }
}
```
<h4 style="text-align:center">
    B.java
</h4>

```java=
package mypack;
import pack.A;
public class B {
    public static void main(String args[]) {
        A obj = new A();
        obj.msg();
    }
}
```
#### Output

```
 Hello
```

### Summary (Visibility Modifiers Summary)

Acs: Accessible
Not Acs: Not Accessible


| Modifier    | Class    | Package  | Subclass| World   |
| ----------- | -------- | -------- | ------- | ------- |
| public      | Acs      | Acs      | Acs     | Acs     |
| protected   | Acs      | Acs      | Acs     | Not Acs |
| no modifier | Acs      | Acs      | Not Acs | Not Acs |
| private     | Acs      | Not Acs  | Not Acs | Not Acs |


## Encapsulation

<p style="text-align:justify">
    The whole idea behind encapsulation is to hide the implementation details from users. If a data member is <B>private</B> it means it can only be accessed within the same class. No outside class can access private data member (fields) of other class. However if we setup public <B>getter</B> and <B>setter</B> methods to update (for e.g. void setAge(int age)) and read (for e.g. int getAge()) the private data fields then the outside class can access those <B>private</B> data fields via public methods. This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better.
</p>

```java=
class Person {
    // Fields
    private String fName;
    private String lName;
    private int age;
    private int ID;
    private static int counter = 0;
    // Only Getter Method for static field counter
    // to guarantee that there is no way to change its value
    // except creating an instance
    public static int getCounter() {
        return counter;
    }
    // A Constructor
    public Person() {
        counter++;
    }

    // Another Constructor
    public Person(String fName, String lName, int age, int ID) {
        this.fName = fName;
        this.lName = lName;
        this.age = age;
        this.ID = ID;
        counter++;
    }

    // Getters and Setters Methods
    public String getfName() {
        return fName;
    }
    public void setfName(String fName) {
        this.fName = fName;
    }
    public String getlName() {
        return lName;
    }
    public void setlName(String lName) {
        this.lName = lName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getID() {
        return ID;
    }
    public void setID(int ID) {
        this.ID = ID;
    }
}
```


###### tags: `Computer Programming II` `Pre-Lab` `IUG` `Computer Engineering`

<center>End Of Pre-Lab 2</center>