Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Lecture 4 - Objects and Classes

The document discusses objects and classes in object-oriented programming using Java. It defines that objects have attributes and behaviors. Classes are blueprints that define attributes as variables and behaviors as methods. The document uses a car as an example class and demonstrates how to define attributes, methods, create objects, and call methods on objects.

Uploaded by

Mtoi Tv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 4 - Objects and Classes

The document discusses objects and classes in object-oriented programming using Java. It defines that objects have attributes and behaviors. Classes are blueprints that define attributes as variables and behaviors as methods. The document uses a car as an example class and demonstrates how to define attributes, methods, create objects, and call methods on objects.

Uploaded by

Mtoi Tv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

University of Dar es Salaam

CS 234: Object-Oriented
Programming in Java
Lecture – Objects and Classes

Aron Kondoro
University of Dar es Salaam
Introduction
• Objects and classes form the basis for object-oriented programming
in Java.
• Any object, phenomenon, or event that you wish to model and
represent in a program has
• Attributes
• Behaviour
University of Dar es Salaam
Analogy
• A car has many attributes
• Colour, number of doors etc
• A car has behaviours. It can
• move forward, steer (change direction) etc
University of Dar es Salaam
Attributes
• Attributes are the characteristics of public class Car {
// Attributes of the car
an object. String color;
String brand;
• In the case of a car, these could String model;
include color, brand, model, and Double engineSize;
}
engine size.
• These are represented in Java as
variables within a class.
University of Dar es Salaam
Behaviour public class Car {
// Method to start the car
• Behaviors are the actions that an public void startEngine() {
System.out.println("Engine
object can perform. started!");
• For a car, behaviors might include }

starting the engine, accelerating, // Method to accelerate the car


public void accelerate() {
and braking. System.out.println("Car is
accelerating!");
• These are implemented as methods }

in Java. // Method to apply brakes


public void applyBrakes() {
System.out.println("Brakes
applied!");
}
}
University of Dar es Salaam
Objects: Conceptual Meaning
• Objects represent things in the problem domain.
• Examples:
Application Objects Attributes and Behaviors
Social Media Application User name, email, and a list of friends
Post content, timestamp, and number of likes
Comment content, timestamp, and the user
E-commerce Application Product name, price, and description
Shopping cart add/remove products and calculate the total price
Order list of products, shipping address, and payment details
Banking Application Account account number, balance, and account holder information
Transaction amount, timestamp, and transaction type
Customer name, address, and a list of accounts
University of Dar es Salaam
What is an Object?
• An object in Java encapsulates both data and behaviour (methods).
• A set of values and operations on them
• An object has three characteristics
• State: represents the data (value) of an object
• Behaviour: represents the behaviour (functionality) of an object
• Identity: way to identify each object uniquely
University of Dar es Salaam
Object-Oriented Programming
• Create your own objects
• Set of values and their operations
• Use them in your programs
• Manipulate objects that hold value
University of Dar es Salaam
What is a Class?
• A Class is a definition (or blueprint) for a kind of object.
• A class defines:
• attributes – properties of the object of this class
• behaviour - what it can do
• states - how behaviour depends on values of attributes
University of Dar es Salaam
Class as a data type
• The most important thing to understand about a class is that it
defines a new data type.
• Once defined, this new type can be used to create objects of that type.
• Thus, a class is a template for an object, and an object is an instance
of a class.
University of Dar es Salaam
Why use classes?
• Why not just primitives?
// Landcruiser
String nameCruiser;
Int numberOfDoorsCruiser

// Rav4
String nameRav4
Int numberOfDoorsRav4
University of Dar es Salaam
Why use classes?
• What if 200 RAV4s?

Terrible
University of Dar es Salaam
Why use classes?

Name Name Name


No. of doors No. of doors No. of doors
Fuel type Fuel type Fuel type 197 more
Engine size Engine size Engine size cars…
… … …

Car 1 Car 2 Car 3


University of Dar es Salaam
Why use classes?

Name Name Name


No. of doors No. of doors No. of doors
Fuel type Fuel type Fuel type 197 more
Engine size Engine size Engine size cars…
… … …

Car 1 Car 2 Car 3

Garage
University of Dar es Salaam
Why use classes?

More
Mechanic 1 Mechanic 2 Mechanic 3 mechanics…

197 more
cars…
Car 1 Car 2 Car 3

Garage
University of Dar es Salaam

Defining Classes
University of Dar es Salaam
Class Design
• When you design a class, think about the
objects that will be created from that class
type. Think about:
• things the object knows
• things the object does
• Things an object knows about itself are
called instance variables
• Things an object can do are called
methods
University of Dar es Salaam
Let’s declare a Car

Public Class Car {


fields • Class names are capitalized
• 1 class = 1 file
methods

}
University of Dar es Salaam
Car fields
public class Car {
public class Car { // Attributes of the car
String color = “Red”;
TYPE var_name;
String brand = “Toyota”;
TYPE var_name = some_value; String model = “Corolla”;
} Double engineSize = 1.8;
}
University of Dar es Salaam
Car methods
public class Car {
// Method to start the car
public void startEngine() {
System.out.println("Engine started!");
}

// Method to accelerate the car


public void accelerate() {
System.out.println("Car is accelerating!");
}

// Method to apply brakes


public void applyBrakes() {
System.out.println("Brakes applied!");
}
}
University of Dar es Salaam
Car Class
public class Car {
// Attributes
String color = “Red”;
String brand = “Toyota”;
String model = “Corolla”;
double engineSize = 1.8;

// Method to start the car


public void startEngine() {
System.out.println("Engine started!");
}

// Method to accelerate the car


public void accelerate() {
System.out.println("Car is accelerating!");
}

// Method to apply brakes


public void applyBrakes() {
System.out.println("Brakes applied!");
}
}
University of Dar es Salaam
Instantiate (Create) the object

Car myCar = new Car();


University of Dar es Salaam
main Method
• The Class Car is not java applications because it does not contain the
main method.
• Therefore, if you execute e.g. Car.class (after compiling Car.java) you will get
an error message.
• To fix this problem, we must either declare a separate class that
contains a main method or place a main method in class Car.
• In this example, we create a new class CarTest to test the Car class.
University of Dar es Salaam
Creating objects & calling methods
public class CarTest {
public static void main(String[] args) {
Car myCar = new Car();

// Using the car's methods


myCar.startEngine();
myCar.accelerate();
myCar.applyBrakes();
}
}
University of Dar es Salaam
Classes and Instances
public class CarTest {
public static void main(String[] args) {
Car rav4 = new Car();
Car ist = new Car();

}
}
University of Dar es Salaam
Accessing fields

Car rav4 = new Car();


System.out.println(rav4.colo
Object.FIELDNAME
r);System.out.println(rav4.bran
d);
University of Dar es Salaam
Calling methods

Object.METHODNAME([ARGUMENTS]);

Car rav4 = new Car();


rav4.increaseSpeed(50)
University of Dar es Salaam
Method that returns a value
• The previous increaseSpeed( ) method increases the speed and
displays the new value once it is called.
• What if another part of the program wanted to increase the speed,
but not display its value?
• A better way to implement increaseSpeed( ) is to have it compute
the speed and return the result to the caller.
University of Dar es Salaam
Method with a return type
public class Car {
// fields
String type = "Toyota";
String model = "Rav 4";
String color = "Black";
int speed = 0;

// methods
void describe() {
System.out.println("Car type: " + type);
System.out.println("Car model: " + model);
System.out.println("Car color: " + color;

int increaseSpeed (int increment) ‹


this. speed = this.speed + increment;
return this. speed;
}
University of Dar es Salaam

Constructors
University of Dar es Salaam
Constructors
• Typically, you can not call a method that belongs to another class until
you create an object of that class.
• For example, this is done by the following line in class CarTest:

• Keyword new creates a new object of the class specified to the right
of the keyword (i.e., Gar).
University of Dar es Salaam
Constructors
University of Dar es Salaam
Constructors
• Constructor name == the class name
• No return type – never returns anything
• Usually, initialize fields
• All classes need at least one constructor
University of Dar es Salaam
Constructors
• A constructor does look and feel a lot like a method, but it's not a
method. It has the code that runs when you instantiate an object.
• The only way to invoke a constructor is with the keyword new
followed by the class name.
• But where is the constructor? In our previous programs, we didn't
write It, who did?
• You can write a constructor for your class, but if you don't, the
compiler writes one for you!
University of Dar es Salaam
Car constructor
University of Dar es Salaam
Constructors
• It can be tedious to initialize all the variables in a class each time an
instance is created.
• Java allows objects to initialize themselves when they are created. This
automatic initialization is performed using a constructor.
• It is the constructor’s job to initialize the internal state of an object so that
the code creating an instance will have a fully initialized, usable object
immediately.
• If you don't put a constructor in your class, the compiler puts in a default
constructor. The default constructor is always a no-arg constructor.
public Car () { }
University of Dar es Salaam
Constructors
• You can have more than one constructor in your class, as long as the
argument lists are different. Having more than one constructor in a
class means you have overloaded constructors.
public Car () { };
public Car(int speed) { };
public Car(String type) { };
public Duck (String type, String model, String color) { };
University of Dar es Salaam

References vs Values
University of Dar es Salaam
Primitives vs References
• Primitive types are basic java types
• int, long, double, boolean, char, short, byte, float
• The actual values are stored in the variable

• Reference types are arrays and objects


• String, int[], Car, …
University of Dar es Salaam
How java stores primitives
• Variables are like fixed-size cups
• Primitives are small enough that they just fit into the cup
University of Dar es Salaam
How java stores objects
• Objects are too big to fit in a variable
• Stored somewhere else
• Variable stores a number that locates the object
University of Dar es Salaam
References
Car ist1 = new Car(“ist”);
Car ist2 = new Car(“ist”);

Name = “ist”

Name = “ist”

ist1 ist2
University of Dar es Salaam

Class and Instance Members


University of Dar es Salaam
Class vs Instance methods
• A static method (aka class method) means no object (instance) of the
class is needed to use the method
• A non-static method (aka instance method) means the method must
be applied to an object (instance of that class)
• For example
• All methods in the Math class are class methods
• All methods in the Scanner class are instance methods
• The String class has both class and instance methods
University of Dar es Salaam
Class and Instance members
• A class has 2 types of members: attributes & methods
• Java provides the modifier static to indicate if the member is a class
member or instance member
University of Dar es Salaam
Static modifier
• Applies to fields and methods
• Means the field/method
• is defined for the class declaration
• is not unique for each instance
University of Dar es Salaam
Calling a class Method

Precede method with class name


University of Dar es Salaam
Calling a class Method
Optional to precede with the
class name if the method is
defined in the same class
University of Dar es Salaam
Calling a instance method
• You have to create an instance (object) first
University of Dar es Salaam
Example of classes in the Java API
• Scanner Class
• For reading input
• https://docs.oracle.com/javase/8/
docs/api/java/util/Scanner.html
• Import java.util.Scanner

next() hasNext()
nextDouble() hasNextDouble()
nextLine() hasNextLine()
University of Dar es Salaam
Scanner Demo
University of Dar es Salaam
Example of classes in the Java API
• String Class
• Various string related methods
• https://docs.oracle.com/en/java/javase/11
/docs/api/java.base/java/lang/String.html
• Import java.lang.String (optional)

char()
concat()
equals()
indexOf()
length()
substring()
University of Dar es Salaam
String Demo
University of Dar es Salaam
Example of classes in the Java API
• Math Class
• Performing computations
• https://docs.oracle.com/javase/8/docs/api
/java/lang/Math.html
• Import java.lang.Math (optional)
abs()
ceil()
floor()
max()
min()
pow()
random()

University of Dar es Salaam
Math Demo
University of Dar es Salaam
Exercises
• Date Program
• Create a Java program that models the date
• The date has three attributes: day, month, year.
• Create some objects Date and print their information
• Employee Program
• Java program that models employees
• Each employee has a name and surname and a monthly salary
• The program should create some employees and then increase their salary by
10%, and print their information.
University of Dar es Salaam
Exercises
• Invoice Program
• Java program that models and implements an invoice
• Each invoice has a number of parts and each part has a part number, a
description and a price.
• The program should create some invoices and print their information
University of Dar es Salaam
Exercises
• Heart Rate Program
• Java program that models heart rates, maximum heart rate and the maximum
and minimum target heart rate.
• The heart rate should be modelled with a class and should have name,
surname, birthYear and currentYear.
• The maximum heart rate MHR is based on the formula 220 - age.
• The minimum target HR is based on: 0.5 * MHR
• The maximum target HR is based on: 0.85 * MHR
• The program should create some objects of type Heart Rate and print their
information.
University of Dar es Salaam
Exercises
• Health Profile Program
• Java program that models health profile of persons
• Based on the previous program of Heart Rates: add the gender, height and
weight attribute
• Compute the person's BMI (body mass index): Weight * 703 / (getHeight() *
getHeight() );
• The program should create some objects of type Heart Rate and print their
information.

You might also like