computer programming, i laboratory manual experiment #10
TRANSCRIPT
Think Twice
Code Once
The Islamic University of Gaza
Engineering Faculty
Department of Computer Engineering
Fall 2017
ECOM 2005
Khaleel I. Shaheen
Thanks to Eng. Mohammed Alokshiya
Computer Programming, I
Laboratory Manual
Experiment #10
Objects & Classes
Experiment #10: Objects & Classes
2
What is Object Oriented Programming?
Object-oriented programming (OOP) involves programming using objects. An object represents
an entity in the real world that can be distinctly identified. For example, a student, a desk, a
circle, a button, and even a loan can all be viewed as objects. An object has a unique identity,
state, and behavior.
• The state of an object (also known as its properties or attributes) is represented by
data fields with their current values. A circle object, for example, has a data field radius,
which is the property that characterizes a circle. A rectangle object has the data fields
width and height, which are the properties that characterize a rectangle.
• The behavior of an object (also known as its actions) is defined by methods. To invoke
a method on an object is to ask the object to perform an action. For example, you may
define methods named getArea() and getPerimeter() for circle objects. A circle object
may invoke getArea() to return its area and getPerimeter() to return its perimeter. You
may also define the setRadius(radius) method. A circle object can invoke this method
to change its radius.
Objects of the same type are defined using a common class. A class is a template, blueprint, or
contract that defines what an object’s data fields and methods will be. An object is an instance
of a class. You can create many instances of a class. Creating an instance is referred to as
instantiation. The terms object and instance are often interchangeable. The relationship
between classes and objects is analogous to that between an apple-pie recipe and apple pies:
You can make as many apple pies as you want from a single recipe.
A Java class uses variables to define data fields and methods to define actions. Additionally, a
class provides methods of a special type, known as constructors, which are invoked to create
a new object. A constructor can perform any action, but constructors are designed to perform
initializing actions, such as initializing the data fields of objects.
Experiment #10: Objects & Classes
3
A class is a construct that defines objects of the same type.
Here is a java code to define the above class “Person”:
class Person {
// Fields
String firstName;
String lastName;
int age;
int SSN;
// Constructor
public Person() {
}
// Another Constructor
public Person(String firstName, String lastName, int age,
int SSN) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.SSN = SSN;
}
// method
public String getFullName() {
String fullName = firstName + " " + lastName;
return fullName;
}
}
Class Name: Person
Attributes:
firstName is String
lastName is String
age is integer
SSN is integer
Actions:
getFullName
Person Object 1
Attributes:
firstName: John
lastName: Smith
age: 29
SSN: 120164851
Person Object 2
Attributes:
firstName: Don
lastName: Harvy
age: 45
SSN: 654875455
Experiment #10: Objects & Classes
4
Then you can create an instance “person1” of the class “Person”, using the new operator, and
assign values to its fields using “.” operator:
public static void main(String[] args) {
// Create object p1 using the first constructor
// (new Person())
Person person = new Person();
person.firstName = "John";
person.lastName = "Smith";
person.age = 29;
person.SSN = 120164851;
System.out.println(person.getFullName());
// Create object p1 using the
// second constructor (new Person(fName, lName, age, id))
Person person2 = new Person("John", "Smith", 29, 120164851);
System.out.println(person2.getFullName());
}
Constructors
Constructors are a special kind of methods that invoked to create an object using the new
operator. They have three peculiarities:
A constructor 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 when an object is created. Constructors play
the role of initializing objects.
The constructor has exactly the same name as its defining class. Like regular methods,
constructors can be overloaded (i.e., multiple constructors can have the same name but
different signatures), making it easy to construct objects with different initial data values.
Constructors are used to construct objects. To construct an object from a class, invoke a
constructor of the class using the new operator, as follows:
new ClassName(arguments);
Experiment #10: Objects & Classes
5
Note: A class may be defined without constructors. In this case, a public noarg 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.
The this Reference
The this keyword is the name of a reference that an object can use to refer to itself. You can
use the this keyword to reference the object’s instance members. It can also be used inside a
constructor to invoke another constructor of the same class.
Example
Design a class named “Car” to represent a car. The class contains:
• Two String data fields named model and color that specify the model and color of the
car.
• Three integer data fields named capacity, maxSpeed and manufacturingYear that
specify the capacity, maximum speed and manufacturing year of the car. The default
value of capacity is 4.
• A no-arg constructor that creates a default car.
• A constructor that creates a car with the specified capacity, maxSpeed,
manufacturingYear, model and color.
• A method named toString() that returns all information about the car as string.
Then create two instances of the Car class, with the following info:
1. Model >> I30, color >> Silver, capacity >> 4, maxSpeed >> 240, manufacturingYear >>
2010.
2. Model >> Mercedes 250, color >> Red, capacity >> 4, maxSpeed >> 260,
manufacturingYear >> 2000.
Use toString() method to print the information of a car.
Experiment #10: Objects & Classes
6
Solution:
public class Main {
public static void main(String[] args) {
Car car1 = new Car("I30", "Silver", 4, 240, 2010);
Car car2 = new Car("Mercedes 250", "Red", 4, 260, 2000);
System.out.println(car1.toString());
System.out.println();
System.out.println(car2.toString());
}
}
class Car {
String model;
String color;
int capacity;
int maxSpeed;
int manufacturingYear;
public Car() {
}
public Car(String model, String color, int capacity,
int maxSpeed, int manufacturingYear) {
this.model = model;
this.color = color;
this.capacity = capacity;
this.maxSpeed = maxSpeed;
this.manufacturingYear = manufacturingYear;
}
@Override
public String toString() {
String s = String.format("%-20s%s\n%-20s%s\n%-20s%s" +
"\n%-20s%s\n%-20s%s",
"Model:", model,
"Color:", color,
"Capacity:", capacity,
"Maximum Speed:", maxSpeed,
"Manufacturing Year:", manufacturingYear);
return s;
}
}
Experiment #10: Objects & Classes
7
Static Variables and Methods
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:
Person person1 = new Person("Mohammed", "Ahmed", 23, 120191379);
Person person2 = new Person("Ahmed", "Khaled", 19, 120140000);
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.
If you want all the instances of a class to share data, use static 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.
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.
Experiment #10: Objects & Classes
8
class Person {
// Fields
String firstName;
String lastName;
int age;
int SSN;
static int counter = 0;
// Constructor
public Person() {
counter++;
}
// Another Constructor
public Person(String firstName, String lastName, int age,
int SSN) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.SSN = SSN;
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:
System.out.println(Person.counter);
You can also define static methods. Static methods can be invoked with class name, without
creating objects.
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:
Experiment #10: Objects & Classes
9
Here is a static method example:
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:
The private access modifier is accessible only within class. In the following example, 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 there is compilation error.
Experiment #10: Objects & Classes
10
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:
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.
package pack;
public class A {
void msg() {
System.out.println("Hello");
}
}
package mypack;
import pack.A;
public class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();// Compilation Error
}
}
Experiment #10: Objects & Classes
11
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.
Visibility Modifiers Summary:
Modifier Class Package World
public Yes Yes Yes
protected Yes Yes No
default (no modifier) Yes Yes No
private Yes No No
Example
Design a class named Equation for a quadratic equation ax2 + bx + x = 0. The class contains:
• Private data fields a, b, and c that represent three coefficients.
• A Constructor for the arguments for a, b, and c.
• Three getter methods for a, b, and c.
• A method named getDiscriminant() that returns the discriminant, which is b2 - 4ac.
• The methods named getRoot1() and getRoot2() for returning two roots of the equation
These methods are useful only if the discriminant is nonnegative. Let these methods
return 0 if the discriminant is negative.
Experiment #10: Objects & Classes
12
Solution:
import java.util.Scanner;
public class Equation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a, b, c: ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
QuadraticEquation equation = new QuadraticEquation(a, b, c);
double discriminant = equation.getDiscriminant();
if (discriminant < 0) {
System.out.println("The equation has no roots");
} else if (discriminant == 0) {
System.out.println("The root is " + equation.getRoot1());
} else {
System.out.println("The roots are " + equation.getRoot1()
+ " and " + equation.getRoot2());
}
}
}
class QuadraticEquation {
private double a;
private double b;
private double c;
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
double getA() {
return a;
}
double getB() {
return b;
}
Experiment #10: Objects & Classes
13
double getC() {
return c;
}
double getDiscriminant() {
return b * b - 4 * a * c;
}
double getRoot1() {
if (getDiscriminant() < 0)
return 0;
else {
return (-b + getDiscriminant()) / (2 * a);
}
}
double getRoot2() {
if (getDiscriminant() < 0)
return 0;
else {
return (-b - getDiscriminant()) / (2 * a);
}
}
}
Encapsulation
The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private 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 getter and setter
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 private 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.
Let's see an example to understand this concept better.
Experiment #10: Objects & Classes
14
class Person {
// Fields
private String firstName;
private String lastName;
private int age;
private int SSN;
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.firstName = fName;
this.lastName = lName;
this.age = age;
this.SSN = ID;
counter++;
}
// Getters and Setters Methods
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
Experiment #10: Objects & Classes
15
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSSN() {
return SSN;
}
public void setSSN(int SSN) {
this.SSN = SSN;
}
}
Homework
1. Solve question 9.7 page 361 from the book.
Good Luck
😊