You are on page 1of 31

Course Code: CSE2031Y

Course Name: OOSD

Lecture 4: Objects & Classes

CSE Department
Faculty of Engineering
University of Mauritius
Overview

 Outline the difference between classes


and objects
 Learn the structure and coding of
program with specimen examples.

 List common mistakes

2
Objects
 An object is an abstraction because it represents
only those relevant features of a thing in the
problem-domain that are deemed relevant to the
current purpose and hides those features that are
not relevant.

 All objects have identity and are distinguishable.

 E.g. two apples with the same color, shape and


texture are still individual apples; a person can
eat one and keep the other.

 Objects = state+behaviour+Identity
3
State
 The state of an object represents the condition
that an object is in at a given moment i.e. the
values of all its properties (attributes).
 e.g. The state of an employee object could be:

 The properties of an object are known as


attributes.
4
Behaviour
 An object performs some actions or is
acted upon by other objects. This
defines the behaviour of an object.

 An object’s behavior corresponds to


the set of methods in its class
because operations are implemented
by methods in the object’s class.
5
Identity

 Identity is that property of an object


that distinguishes it from all other
objects. [Booch]

 Identity defines the uniqueness of


each object.

6
Class
 A class describes a group of objects with similar
properties (attributes),common behaviour
(operations/methods), and common relationships to
other objects.

 Objects that are sufficiently similar to each other are


said to belong to the same class i.e. they will share the
same attributes, methods and relationships.

 Examples of classes: Person, Animal, Company


 Examples of objects: John Doe, Dog, Adgate Ltd.
 John Doe, Mary Sharp, Adam Smith are instances of
the class Person…

7
Class structure
 <modifier/s> class ClassName{
 }
 Modifiers can be: public, abstract | final

 E.g.

 class Car{
 //other codes
 }

 Note: If no modifier is used, then default is assumed.

8
Properties
 <modifier/s> <dataType>
propertyName [=var_initializer ]

 Modifiers can be:


public|private|protected, final, static

 E.g public final string Name = “Salil”;

9
Methods/Behaviours
 <modifier/s> <return_dataType> methodName(parameters){
 }

 Modifiers can be: public|private|protected, final,


static|abstract

 E.g.

 public static void calculate(int value){


 //other codes
 }

 Note: If no modifier is used, then default is assumed.

10
Class with attribute and method
 class Student{ //className = ‘Student’
 private name = “Roushdat”; // propertyName = ‘name’
 private id; // propertyName = ‘id’
 public void setId(String id){ //methodName=‘setId’
 this.id =id; // setting value classwide variable ‘id’ to value of parameter
‘Id’

 }
 }

11
Main Class
 The main class allows the execution of a java
program.
 A java program can have many classes, but it
should have at least 1 main class to be
executable
 The main class should contain the main method.
 E.g of a main class
 class StudentMain{ //main class for student program
 Public static void main(String[] args){ //main method of
the class
 Student uomStudent= new student(); // instantiates an
object uomStudent from class Student
 }
12
Constructor (1) – Default Constructor
 The purpose of a constructor is to create an object based on a
class’s blueprint.

 A constructor has the same name as the name of the class


to which it belongs. Constructor’s signature does not include a
return type, since constructors never return a value.

 Each class must have at least 1 constructor; if you do not write


a constructor, java will create a default constructor for you.

 The default constructor does not take any parameters.


 E.g. For a class Student, the default constructor will look like
public Student() {//codes }
 Writing Student myStudent = new Student(); in the main class
will invoke the default constructor from class Car

13
Constructor (2) – Defined Constructor
 Constructors can also take parameters.

 E.g. public Student(String name, String id) {


//codes}

 To invoke this constructor, the user has to


supply the name and id values while creating
the myStudent object in the main class

 i.e. Student myStudent = new Student


(“Roushdat”, “1024534”);
14
Constructor Example
public class Student{
private String name;
private String id;

public Student(){ //default constructor


name="New Student";
id="0000000";
}

public Student(String name, String id){ //defined constructor


this.name=name;
// this keyword used to differentiate
this.id=id; between classwide variable ‘name’
} and constructor parameter ‘name’
}

15
Accessors
 Accessor methods read property
values and are conventionally named
get<FieldName>()
 E.g.
 public int getMark() // accessor method for field mark
 { return Mark; // mark is declared: private int Mark;
 }

16
Mutators
 Mutator methods set property values and are often
named set<FieldName>() etc.
 Mutators can be used to ensure that the property's value
is valid in both range and type.
 E.g.
 public int setMark(int myMark) //mutator method
 { if (myMark >= 0)
 this.mark = myMark
 }else
 {
 this.mark = 0;
 }

17
Specimen - Exercise 1a
 Create a class Person that has classwide
attributes name and age.
 Include Accessor and mutator methods for
every field.
 Include a default constructor that initialises
name to ‘Person’ and age to18
 Include a defined constructor that takes in
values for the two fields (name and age) and
initialises the Person object.
 Include a method display to display the name
and age

18
Answer to Exercise 1a
public class Person { public int getAge(){
private String name; return age;
private int age; }

public void setName(String name){ public Person(){


this.name = name; name = "Person";
}
age = 18;
}
public String getName(){
return name;
} public Person(String name, int age){
this.name = name;
public void setAge(int age){ this.age = age;
if(age<1 || age >120){ }
System.out.println("Invalid age! Age set to default
value 18");
public void display(){
this.age = 18;
System.out.println("Name is: "+name);
}else{this.age=age;}
} System.out.println("Age is: "+age);
}
}

19
Specimen - Exercise 1b
 Create a class PersonMain.

 Include the main method that allow the creation of two


persons object, i.e, Person1 and Person2 respectively.
 Create an object Person1 using the default constructor
 Use the mutator methods to set Person1’s name to
“Jeeten” and age to 40.
 Use the accessor methods to retrieve the attribute
values of Person1 and display them in PersonMain.

 Create an object Person2 using a defined constructor


with the following parameters Name:Roushdat and
Age:25
 Display the attribute values of Person2

20
Answer to Exercise 1b
public class PersonMain {
public static void main(String[] args){
Person Person1 = new Person();
Person1.setName("Jeeten");
Person1.setAge(40);
System.out.println("Name: "+Person1.getName());
System.out.println("Age: "+Person1.getAge());
Person Person2 = new Person("Roushdat",25);
Person2.display();
}
}

21
Output from Exercise 1

22
Specimen - Exercise 2
 You are required to write a program that will
display car details as follows.

 Hint:
 Create a class Car and the main class CarMain.
 In CarMain create an instance of Car called
myCar, then invoke display() on myCar.
23
Specimen - Answer to Ex 2 - i
public class Car {
public static final double VAT = 0.15;
private String CarNo;
private String make;
private String model;
private double price;

public Car(){
CarNo = "27JL11";
make = "Nissan";
model = "Skyline R34";
price = 1950000.00;
}

public void display() {


System.out.println("Car: "+CarNo);
System.out.println("Make & Model: "+make+" "+model);
System.out.println("Price: "+price+"\n");
}
}
24
Specimen - Answer to Ex 2 - ii

public class CarMain {


public static void main(String[] args){
Car myCar = new Car();
myCar.display();
}

25
Static – Without instance
 Static variable
 Sometimes it is desirable to have a
variable that is shared among all
instances of a class. You can achieve
this effect by marking the variable with
the keyword static. Such a variable is
sometimes called a class variable to
distinguish it from a member or
instance variable which is not shared.
26
Static variable example
class Count { public class CountObject {
private int serialNum; public static void main (String
args[]) {
private static int counter =0;
Count product1 = new Count();
Count() {
product1.display();
counter ++;
Count product2 = new Count();
serialNum = counter;
product2.display();
}
Count product3 = new Count();
void display() {
product3.display();
System.out.println(“Serial number:
“ }
+serialNum); } }
}

27
Static Methods
 Sometimes you need to access program code when you do
not have an instance of a particular object available.

 A method that is marked using the keyword static can be used


in this way and is sometimes called a class method.

 A static method can be invoked without any instance of the


class to which it belongs, i.e. methods that are static can be
accessed using the class name rather than a reference.

 Static variables and methods are closely related together.


 Non-static methods can operate with static variables.
 Static methods can only deal with static variables and static
methods.

28
Static methods example
class GeneralFunction { class StaticMethods {
static int addUp(int x, int y) { public static void display () {
return x+y; System.out.println(“This is a static
method.”);
}
}
}
public static void main(String
class UseGeneral {
args[]) {
public void useAdd() {
UseGeneral us = new
int a = 9, b = 10; UseGeneral();
int c = //call the useAdd() to call static
GeneralFunction.addUp(a,b); addUp()
System.out.println(“addUp() gives “ us.useAdd();
+c);
display();
}
}
}
}
29
Representing Classes In UML

30
Some Common Mistakes
 Case sensitivity
 Java is case-sensitive. Among other things, this means that, in a Java
program, the letter P isn’t the same as the letter p.

 //The following line is incorrect:


 System.out.Println(myScanner.nextLine());

 Omitting punctuation (;)

 Using too much punctuation


 you shouldn’t be ending a method header with a semicolon. Except for
Abstract methods

 //The following line is incorrect:


 public static void main(String args[]); {

31

You might also like