Computer Programming (2)
Chapter 1
Classes and Objects
1. Declaring classes, instance variables, methods
2. Default and Explicit Initialization for Instance Variables
3. Constructors, private, public, static.
4. More Examples
Contents
Required Reading
1. Chapter 7 - (Java: How to program: Late Objects)
Recommended Reading
1. Chapter 6 - (Java The Complete Reference, Eleventh Edition)
2. Java Classes and Objects:
https://www.w3schools.com/java/java_classes.asp
• Declaring classes, instance variables, methods
Declaring classes, instance variables, methods
Object Oriented Programming (OOP)
Encapsulates data (attributes) and methods (behaviors)
• Objects
Allows objects to communicate
• Well-defined interfaces
Declaring classes, instance variables, methods
• What are Classes and Objects?
Reference: https://www.w3schools.com/java/java_oop.asp
Declaring classes, instance variables, methods
• A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical
entity. It can't be physical.
• A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Reference: https://www.javatpoint.com/object-and-class-in-java
Declaring classes, instance variables, methods
Person
Ahmed
Majed
Salem
Saad
9
Declaring classes, instance variables, methods
Student
Ahmed
Majed
Salem
Saad
10
Declaring classes, instance variables, methods
Tennis Player
Bandar
Mosaed
Nayef
Khaled
11
Declaring classes, instance variables, methods
Institute
Social Technology
Engineering
Science
Agricultural Technology
12
Declaring classes, instance variables, methods
Name Name
Attributes Data members
Operations Methods
… …
13
Declaring classes, instance variables, methods
Student
StudentID
FirstName
LastName
Address
etc…
RegisterForCourse
DropCourse
etc...
14
Declaring classes, instance variables, methods
Tennis Player
FirstName
LastName
Nationality
Ranking
etc…
RegisterForTournament
etc...
15
Declaring classes, instance variables, methods
Car
Car Reg. Number
Maker
Model
Color
etc…
Accelerate
Stop
etc...
16
Declaring classes, instance variables, methods
Airplane
Plane Number
Manufacturer
Model
etc…
TakeOff
Landing
etc...
17
Declaring classes, instance variables, methods
• An object is an instance of a class. A class is a template or blueprint from
which objects are created. So, an object is the instance(result) of a class.
• Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
• In order to create object :
ClassName objectName = new ClassName();
• Example:
• Employee e1 = new Employee();
Reference: https://www.javatpoint.com/object-and-class-in-java
Declaring classes, instance variables, methods
19
Declaring classes, instance variables, methods
Class: Car Object: a car
Attributes(Data): Attributes:
String model model = “Mustang"
Color color color = Color.YELLOW
int numPassengers numPassengers = 0
double amountOfGas amountOfGas = 16.5
Behaviors (Methods): Behaviors:
Add/remove a passenger
Get the tank filled
Report when out of gas
20
Declaring classes, instance variables, methods
Student
Student StudentID
FirstName
Ahmed LastName
Majed Address
Salem etc…
RegisterForCourse
Saad DropCourse
etc...
21
Declaring classes, instance variables, methods
Student1
Student B4555555
Ahmed
Ahmed Alfahad
Majed 7146 sdasds7
Salem etc…
RegisterForCourse
Saad DropCourse
etc...
22
Declaring classes, instance variables, methods
Attributes
Anything
Behavior
23
Declaring classes, instance variables, methods
• Instance variable in Java
• A variable which is created inside the class but outside the method is known
as an instance variable.
• Instance variable doesn't get memory at compile time.
• It gets memory at runtime when an object or instance is created.
• That is why it is known as an instance variable.
Reference: https://www.javatpoint.com/object-and-class-in-java
Declaring classes, instance variables, methods
• Example:
Declaration Creation
Declaring classes, instance variables, methods
• In order to refer to a particular instance variable, preface it with its
object name as follows:
objectName.instanceVar1
objectName.instanceVar2
• Example:
• e1.name
• e1.age
• e1.salary
• To change the name of e1:
• e1.name = "Mohamed";
Declaring classes, instance variables, methods
Method in Java
In Java, a method is Methods in classes
like a function which represent a behavior
is used to expose the of an object from the
behavior of an object. class
Reference: https://www.javatpoint.com/object-and-class-in-java
Declaring classes, instance variables, methods
• In order to invoke a method of a class, you need an object of
that class:
• objectName.method1()
• objectName.method2(argument1)
• Example:
• e1.outputDetails();
Encapsulation
• Data Hiding
• Abstraction
• Security
29
Encapsulation (data hiding)
• The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must:
• declare class variables/attributes as private
• provide public get and set methods to access and update the value of
a private variable
• Encapsulation allows the programmer to group data and the methods
that operate on them together in one place, and to hide details from
the user.
wit
it hDr withDraw any value
os
p o
aw
De untN
o
Acc
AccountValue
Change Address e r
Name Address ns
f
a
Tr
Print
30
Encapsulation (data hiding)
Sell (1 SR, Pepsi)
Vending
Person
Machine
Sell
Buy Pepsi
31
Declaring classes, instance variables, methods
• Example:
Declaring classes, instance variables, methods
• Instance Variable name
• Instance variables are declared inside a class declaration but outside the
bodies of the class’s methods
• Access Modifiers public and private
• Variables or methods declared with access modifier public are accessible from outside
the class in which they’re declared.
• Variables or methods declared with access modifier private are accessible only to
methods of the class in which they’re declared.
Accessor and Mutator Methods
• The methods that modify the data of fields are called mutators.
• The name of a mutator method starts with the word set
• Instance Method setName of Class Account
• indicates that setName receives parameter name of type String—which
represents the name that will be passed to the method as an argument.
• If a method contains a local variable with the same name as an instance
variable, the method’s body can use the keyword this to refer to the
shadowed instance variable explicitly
Accessor and Mutator Methods
• The methods that retrieve the data of fields are called accessors.
• The data can be accessed but not changed
• The name of an accessor method starts with the word get
• Instance Method getName of Class Account
Declaring classes, instance variables, methods
• AccountTest Class That Creates and Uses an Object of Class Account
Output
Declaring classes, instance variables, methods
• Instantiating an Object—Keyword new
• Keyword new creates a new object of the specified class—in this case,
Account.
• The parentheses to the right of Account are required.
Declaring classes, instance variables, methods
static Methods
Recall that static methods relate to a class as a whole
Whereas instance methods are associated with a specific instance (object)
of the class and may manipulate the instance variables of that object.
• Default and Explicit Initialization for Instance Variables
Default and Explicit Initialization for Instance Variables
• Recall that local variables are not initialized by default.
• Primitive-type instance variables are initialized by default
• Instance variables of types byte, char, short, int, long, float and double are
initialized to 0, and variables of type boolean are initialized to false.
• You can initialize an instance variable as:
Chapter 2
Constructors and Encapsulation, toString
• Constructors, private, public.
Constructors, private, public, static.
• Each class you declare can optionally provide a constructor with
parameters that can be used to initialize an object of a class when the
object is created.
• It has the same name as its class and is syntactically similar to a method.
• However, constructors have no type returned, not even void.
Constructors, private, public, static.
Constructor
Constructors, private, public, static.
• How Constructors are called:
Ø A constructor is called when an object of the class
is created using new
ClassName objectName = new ClassName(anyArgs);
• Example:
Employee e1 = new Employee("Mohamed", 20, 5000);
Constructors, private, public, static.
Constructor
Calling the constructor
Constructors, private, public, static.
Include a No-Argument Constructor:
• If you do not include any constructors in your class, Java will automatically
create a default or no-argument constructor that takes no arguments,
performs no initializations, but allows the object to be created
• If you include even one constructor in your class, Java will not provide this
default constructor
• If you include any constructors in your class, be sure to provide your own
no-argument constructor as well
Constructors, private, public, static.
• No-argument constructor example:
No-argument
constructor
Constructors, private, public, static.
• Example:
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
Output
100 100
Reference: https://www.javatpoint.com
Constructors, private, public, static.
• Parameterized Constructors example:
// A simple constructor.
class MyClass {
int x;
MyClass(int i ) {
x = i;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
Output
10 20
Reference: https://www.javatpoint.com
Constructors, private, public, static.
• If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects
• The static variable gets memory only once in the class area at the time of
class loading.
class Student{
int rollno;
String name;
String college="ITS";
}
Reference: https://www.javatpoint.com
Constructors, private, public, static.
class Student{ class Student{
int rollno; int rollno;//instance variable
String name; String name;
String college="ITS"; static String college ="ITS";//static variable
} Student(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
}
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Output Student s2 = new Student(222,"Aryan");
s1.display();
111 Karan ITS s2.display();
222 Aryan ITS }
}
Reference: https://www.javatpoint.com
Constructors, private, public, static.
• Program of the counter without static variable
class Counter{
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects Output
Counter c1=new Counter();
Counter c2=new Counter(); 1
Counter c3=new Counter(); 1
} 1
}
Reference: https://www.javatpoint.com
Constructors, private, public, static.
• Program of the counter with static variable
class Counter{
static int count=0;
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects Output
Counter c1=new Counter();
Counter c2=new Counter(); 1
Counter c3=new Counter(); 2
} 3
}
Reference: https://www.javatpoint.com
Constructors, private, public, static.
• Static Method Example:
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result); Output
}
} 125
Reference: https://www.javatpoint.com
Constructors, private, public, static.
• Public Modifier
package abcpackage;
public class Addition {
Public int addTwoNumbers(int a, int b){
return a+b;
}
} Output
31
package xyzpackage;
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
obj.addTwoNumbers(10, 21);
}
}
Reference: https://beginnersbook.com/2013/05/java-access-modifiers/
Constructors, private, public, static.
• Private Modifier
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
Output
}
Compile - time error
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Reference: https://beginnersbook.com/2013/05/java-access-modifiers/
• More Examples
Implementing a test class
• Example 1:
class Lamp {
// stores the value for light
// true if light is on
// false if light is off
boolean isOn;
// method to turn on the light
void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn); Output
}
// method to turnoff the light
void turnOff() { Light on? true
isOn = false;
System.out.println("Light on? " + isOn); Light on? False
}
}
class Main {
public static void main(String[] args) {
// create objects led and halogen
Lamp led = new Lamp();
Lamp halogen = new Lamp();
// turn on the light by calling method turnOn()
led.turnOn();
// turn off the light by calling method turnOff()
halogen.turnOff();
}
}
Reference: https://www.programiz.com/java-programming/class-objects
Implementing a test class
class Account{
• Example 2: int acc_no;
String name;
float amount;
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
}
//method to check the balance of the account
void checkBalance(){System.out.println("Balance is: "+amount);}
//method to display the values of an object
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
Reference: https://www.javatpoint.com/object-and-class-in-java
Implementing a test class
• Example 2:
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000); Output
a1.display();
a1.checkBalance(); 832345 Ankit 1000.0
a1.deposit(40000); Balance is: 1000.0
a1.checkBalance(); 40000.0 deposited
a1.withdraw(15000); Balance is: 41000.0
a1.checkBalance(); 15000.0 withdrawn
} Balance is: 26000.0
}
Reference: https://www.javatpoint.com/object-and-class-in-java
• toString Method
The method toString
• The purpose of the toString method is to return a
String value that represents the data in the object
public String toString()
The method toString
• Example:
Output
name:Mohamed, age:20, salary:5000.0
toString invocation
References
• Deitel, P. J., & Deitel, H. M. (2017). Java: how to program late objects.
Pearson.
Thank You