You are on page 1of 51

Objects and Classes

1
What is OOP?
What is OOP?
• Object-oriented programming (OOP) is an engineering
approach for building software systems
• Based on the concepts of classes and objects that are used
for modeling the real world entities
• Object-oriented programs
• Consist of a group of cooperating objects
• Objects exchange messages, for the purpose of achieving a
common objective
• Implemented in object-oriented languages
3
OOP in a Nutshell
• A program models a world of interacting objects
• Objects create other objects and “send messages” to each
other (in Java, call each other’s methods)
• Each object belongs to a class
• A class defines properties of its objects
• The data type of an object is its class
• Programmers write classes (and reuse existing classes)

4
What are OOP’s Claims To Fame?

• Better suited for team development


• Facilitates utilizing and creating reusable software
components
• Easier GUI programming
• Easier software maintenance

• All modern languages are object-oriented: Java, C#, PHP,


Perl ...
5
Classes and Objects
What Are Objects?
• Software objects model real-world objects or abstract
concepts
• E.g. dog, bicycle, queue
• Real-world objects have states and behaviors
• Dogs' states: name, color, breed, hungry
• Dogs' behaviors: barking, fetching, sleeping

7
What Are Objects?
• How do software objects implement real-world objects?
• Use variables/data to implement states
• Use methods/functions to implement behaviors
• An object is a software bundle of variables and related
methods

8
Classes
• Classes provide the structure for objects
• Define their prototype
• Classes define:
• Set of attributes
• Also called state
• Represented by variables and properties
• Behavior
• Represented by methods
• A class defines the methods and types of data associated
with an object 9
Objects
• Creating an object from a class is called instantiation
• An object is a concrete instance of a particular class
• Objects have state
• Set of values associated to their attributes
• Example:
• Class: Account
• Objects: Ivan's account, Peter's account

10
Classes – Example

Class
Attributes
Account
+Owner: Person
+Ammount: double
+suspend()
+deposit(sum:double)
+withdraw(sum:double) Operations

11
Classes and Objects – Example

Class Object ivanAccount


+Owner="Ivan Kolev"
+Ammount=5000.0
Account
+Owner: Person
+Ammount: double
Object peterAccount
+suspend() +Owner="Peter Kirov"
+deposit(sum:double) +Ammount=1825.33
+withdraw(sum:double)

kirilAccount
Object +Owner="Kiril Kirov"
+Ammount=25.012
Messages
• What is a message in OOP?
• A request for an object to perform one of its operations
(methods)
• All communication between objects is done via messages

13
An object has unique
identity, State and behaviors

State(attributes)
consists of a set of
data fields
(properties) with their
current values.

Behavior(operati
ons) of an object is
defined by a set of
methods.

14
Classes
 Classes:
◦ People,books,dogs,cats,cars,airplanes,trains,etc.
 Instance of a class
◦ You, your parents, the book you are reading, the car you
drive
Example: Car class
Property names Method Names
model startEngine
year stopEngine
Color accelerate

15
public class Student {
private String name;
private String studentID;
private String surname;
private Course takenCourse;
private int state;
public void takeCourse(Course course) {
.
.
.
}
public void payTuition() {
.
.
.
}
} 16
Objects

An object has both a state and behavior. The state defines the
object, and the behavior defines what the object does.
17
Variables
 A class can contain any of the following variable types.
 Local variables: Variables defined inside methods,

constructors or blocks are called local variables. The variable


will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
 Instance variables: Instance variables are variables within a

class but outside any method. These variables are initialized


when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of
that particular class.
 Class variables: Class variables are variables declared with in a

class, outside any method, with the static keyword.


18
Creating an Object
 Class provides the templete for objects. So basically an object
is created from a class. In Java, the new key word is used to
create new objects.

 There are three steps when creating an object from a class:

 Declaration: A variable declaration with a variable name with an


object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a

constructor. This call initializes the new object.


19
Example
public class Puppy{
public Puppy(String name){
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){

// Following statement would create an object myPuppy

myPuppy = new Puppy( "tommy" );


}
}

20
class Planet
{
public double radius;
public String name;
public static final long g = 10;
public void display() class ExPlanet
{ {
System.out.println("Radius "+ radius); public static void main(String[]
System.out.println("Name " + name); args) {
System.out.println("Long "+ g); Planet p = new Planet();
p. initialize();
} p.display();
public void initialize()
{ }
radius = 10; //usage }
name = "Dunya"; //usage
}
}

21
Classes

 Classes are constructs that define objects of the same type.

 A Java class uses variables to define data fields and methods to


define behaviors.

 A class provides a special type of methods, known as constructors,


which are invoked to construct objects from the class.

22
Constructors
Constructors are a special kind of methods that are invoked to
perform initializing actions.

Circle() {

}
Circle(double newRadius)
{
radius = newRadius;
}

23
Constructors, cont.
 A constructor with no parameters is referred to as a no-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 when an object
is created. Constructors play the role of initializing objects.

24
Creating Objects Using Constructors

new ClassName();

Example:
new Circle();

new Circle(5.0);

25
Classes

26
class Emp
{
private String name;
private String id;
private int salary;
Emp() // default constructor. No argument list
{
name = “Ali";
id = "1234";
salary = 100;
}
public Emp(String n, String i, int s) // non-default constructor
{
name = n;
id = i;
salary = s;
}
void display()
{
System.out.println("\nEmploye Info ");
System.out.println("Name "+ name);
System.out.println("ID "+ id);
System.out.println("Salary "+ salary);
}
}
27
class ExEmp
{
public static void main(String [] args)
{
Emp e1 = new Emp();
e1.display();
Emp e4 = new Emp("Aleena","98745", 400);
e4.display();
}
}

28
Default Constructor

 A class may be declared without constructors.


 In this case, a no-arg constructor with an empty body is
implicitly declared in the class.
 This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly declared
in the class.

29
public class Student {
private String name;
private String studentID;
private String surname;
private Course[] takenCourses;
private int state;
public Student(String nameParam,String surnameParam) {
name=nameParam;
surname=surnameParam;
}
public static void main(String[] args) {
Student s1 = new Student(“Muhammad”,”Ali”);
}
}

30
Declaring/Creating Objects
in a Single Step

ClassName objectRefVar = new ClassName();

Example:
Circle myCircle = new Circle();

31
Accessing Objects
 Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

 Invoking the object’s method:

objectRefVar.methodName(arguments)
e.g., myCircle.getArea()

32
Example
class Student1{  
 int id; //data member (also instance variable)  
 String name; //data member(also instance variable)  
  
 public static void main(String args[]){  

  Student1 s1=new Student1(); //creating an object of Student  
  System.out.println(s1.id);  
  System.out.println(s1.name);  
 }  
}  
33
// Define the circle class with two constructors
class Circle1 { public class TestCircle1 {
double radius; public static void main(String[] args)
{
/** Construct a circle with radius 1 */ // Create a circle with radius 5.0
Circle1() { Circle1 myCircle = new Circle1(5.0);
radius = 1.0;
} System.out.println("The area of the circle of radius " + myCircle.radius + " is
" + myCircle.getArea());
/** Construct a circle with a specified radius */
Circle1(double newRadius) { // Create a circle with radius 1
radius = newRadius; Circle1 yourCircle = new Circle1();
} System.out.println("The area of the circle of radius " + yourCircle.radius + "
is " + yourCircle.getArea());
/** Return the area of this circle */
double getArea() { // Modify circle radius
return radius * radius * Math.PI; yourCircle.radius = 100;
} System.out.println("The area of the circle of radius " + yourCircle.radius + "
} is " + yourCircle.getArea());
}
}

34
Object vs. Class
Class Object
A template for declaring and creating An instance of a class
the objects
No memory is allocated at the time of Memory is allocated at the time of
creation creation
Has to be declared only once. Multiple objects can be created for a
single class
A class is a logical entity An object is a physical entity
Example: Car Example: Honda, Toyota, Suzuki
Overloading Constructors

 Classes can have more than one constructor


 All constructors have the same name (the class name)
 Each constructor differs from the others in either the number
or types of its arguments
 It is used when using a constructor to create a new object

36
Overloading Constructor Methods
1. public StudentRecord(){e initialization code here
}
2. public StudentRecord(String temp){
name = temp;
}
3. public StudentRecord(String name1, String address2){
name = name1;
address = address2;
}
4. public StudentRecord(double mGrade, double eGrade,double sGrade){
mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
}

37
Using Constructors

To use these constructors, we have the following code,

public static void main( String[] args )


{
//create three objects for Student record
StudentRecord aRecord=new StudentRecord(“Ahmed");
StudentRecord bRecord=new StudentRecord(“BESE“, “Pakistan");
StudentRecord cRecord=new StudentRecord(80,90,100);
//some code here
}

38
Summary
Instance variable in Java
 A variable that is created inside the class but outside the method, is known as

instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when object(instance) is created. That is why, it is known as
instance variable.

Method in Java
 In java, a method is like function i.e. used to expose behavior of an object.

Advantage of Method
 Code Reusability
 Code Optimization

new keyword
 The new keyword is used to allocate memory at runtime.

39
this keyword in java
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class
instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class
method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current
class instance.

40
class JBT {
int variable = 5;
public static void main(String args[]) {
JBT obj = new JBT(); // obj creation
obj.method(20);
obj.method();
}
void method(int variable) {
variable = 10;
System.out.println("Value of Instance variable :" + this.variable);
System.out.println("Value of Local variable :" + variable);
}
void method() {
int variable = 40;
System.out.println("Value of Instance variable :" + this.variable);
System.out.println("Value of Local variable :" + variable);
}
} 41
output
 Value of Instance variable :5
 Value of Local variable :10
 Value of Instance variable :5
 Value of Local variable :40

42
Defining a method/Function
A typical method declaration:
public double calculateAnswer(float length, double grossTons) {
//do the calculation here
}
The only required elements of a method declaration are the
 Access modifier
 method's return type,
 name,
 a pair of parentheses, (),
 and a body between braces, {}.

43
Signature of the method
 Two of the components of a method declaration comprise the
method signature—the method's name and the parameter
types

calculateAnswer(float, double)

44
Overloading Methods

 The Java programming language supports overloading


methods, and Java can distinguish between methods with
different method signatures.

 This means that methods within a class can have the same
name if they have different parameter lists

45
public class DataArtist {
...
public void draw(String s) {
... }
public void draw(int i) {
... }
public void draw(double f) {
... }
public void draw(int i, double f) {
... }
}

46
Overloading Methods
 Overloaded methods are differentiated by the number and the
type of the arguments passed into the method.

 In the code sample, draw(String s) and draw(int i) are distinct


and unique methods because they require different argument
types.

 You cannot declare more than one method with the same
name and the same number and type of arguments, because
the compiler cannot tell them apart.

47
Example 1: Overloading – Different
Number of parameters in argument list
class DisplayOverloading {
public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
}

class Sample {
public static void main(String args[]) {
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
48
Example 2: Overloading – Difference in
data type of arguments
class DisplayOverloading2 {
public void disp(char c) {
System.out.println(c);
}
public void disp(int c) {
System.out.println(c );
}
}
class Sample2 {
public static void main(String args[]) {
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}
49
Example3: Overloading – Sequence of data type of arguments

class DisplayOverloading3 {
public void disp(char c, int num) {
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c) {
System.out.println("I’m the second definition of method disp" );
}
}

class Sample3 {
public static void main(String args[]) {
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
} 50
Class Activity
 Create a student class
◦ Having 2 instance variables: int rollno;   String name
◦ Have 2 methods insertRecord()
◦ displayInformation()
 Create two objects of Student class
 Initializing the value to these objects by invoking the

insertRecord method on it.


 Displaying the state (data) of the objects by invoking the

displayInformation method.

51

You might also like