0% found this document useful (0 votes)
22 views

Week 2 Slides

This document discusses object-oriented programming (OOP) and basic object concepts in Java. It covers that OOP is a programming paradigm based on constructing and using objects that interact. Classes define new types of objects that have instance variables to store data and instance methods to perform actions. The document explains how to define a class, create objects from a class, access an object's instance variables and methods, and use instance methods that can only be called on instantiated objects.

Uploaded by

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

Week 2 Slides

This document discusses object-oriented programming (OOP) and basic object concepts in Java. It covers that OOP is a programming paradigm based on constructing and using objects that interact. Classes define new types of objects that have instance variables to store data and instance methods to perform actions. The document explains how to define a class, create objects from a class, access an object's instance variables and methods, and use instance methods that can only be called on instantiated objects.

Uploaded by

Shudipto Podder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

COMP 1020 -

Basic objects

1
OOP
• OOP stands for Object Oriented Programming

2
OOP
• OOP stands for Object Oriented Programming

• It is a programming model, or paradigm, based on


the construction and use of objects:

• a program built under this model can be seen as a


set of objects interacting together

3
OOP
• OOP stands for Object Oriented Programming

• It is a programming model, or paradigm, based on


the construction and use of objects:

• a program built under this model can be seen as a


set of objects interacting together

• Many programming languages support OOP

4
OOP
• In this course, we’re going to see the basic concepts
of objects and how they work in Java

5
OOP
• In this course, we’re going to see the basic concepts
of objects and how they work in Java

• There is a second-year course focusing entirely on


the concepts of object oriented programming:
COMP 2150 - Object orientation (Winter)
• COMP 2150 goes a lot deeper into the concepts
of OOP and shows you how they work in three
different languages: Java, C++ and Ruby

6
OOP
• In this course, we’re going to see the basic concepts
of objects and how they work in Java

• There is a second-year course focusing entirely on


the concepts of object oriented programming:
COMP 2150 - Object orientation (Winter)
• COMP 2150 goes a lot deeper into the concepts
of OOP and shows you how they work in three
different languages: Java, C++ and Ruby
• Very important that you understand the basic
concepts to get ready for 2150
7
The purpose of class
• Breaking news: a class is not just a container in which
we put a main method

public class MyProgram {

public static void main (String[] args) {

System.out.println(“Hello!”);
}
}

8
Class means type
• When you create a class, you’re actually defining a new
type of data (i.e. an object)

9
Class means type
• When you create a class, you’re actually defining a new
type of data (i.e. an object)
• Like any other type, a class has:
• A name (the class name, which should begin with
an uppercase letter by convention)

10
Class means type
• When you create a class, you’re actually defining a new
type of data (i.e. an object)
• Like any other type, a class has:
• A name (the class name, which should begin with
an uppercase letter by convention)
• Some kind of data that is stored: a collection of
variables called instance variables (& class variables)

11
Class means type
• When you create a class, you’re actually defining a new
type of data (i.e. an object)
• Like any other type, a class has:
• A name (the class name, which should begin with
an uppercase letter by convention)
• Some kind of data that is stored: a collection of
variables called instance variables (& class variables)
• Some kind of actions that can be performed on the
data: a collection of methods called instance
methods (& class methods)
12
Use of objects
• Objects in programs are often used to represent real
life objects…

• person, student, car, bank account, store, etc.

• … or more abstract concepts, such as data structures


or GUI elements

• list, tree, node, panel, button, etc.

13
Class definition
• A class is defined in a .java file, with the same name
as the class

14
Class definition
• A class is defined in a .java file, with the same name
as the class

• Example:

public class Person{


public String name;
public int age;
}

15
Class definition
• A class is defined in a .java file, with the same name
as the class

• Example:
This is just the class definition,
i.e a specification / model /
public class Person{
template for your new type 
public String name; it does not create anything in
public int age; memory.
} When you actually build an
instance of this class, you get
what we call an object.

16
Class definition
• A class is defined in a .java file, with the same name
as the class

• Example: These are the instance


variables, i.e. the object’s
public class Person{ data  each instance will
public String name; have its own specific set of
public int age; values for the instance
variables.
}
We’ll talk about the “public”
later.

17
Class definition
• A class is defined in a .java file, with the same name
as the class

• Example:

public class Person{ We normally assign values to


public String name; the instance variables in the
public int age; constructor  we’ll see that
} in a bit

18
Class definition
• A class is defined in a .java file, with the same name
as the class

• Example:

public class Person{ When you compile this file,


public String name; you get a Person.class file
public int age; (as expected), and then
} you’re ready to use your
new type called Person

19
Creating objects
• Once your class has been compiled, you use this new
type, in a main for example:
Person john;
Person jane;

20
Creating objects
• Once your class has been compiled, you use this new
type, in a main for example:
Person john;
Person jane;

• What you see above is just a declaration, no object


has been created yet

21
Creating objects
• Once your class has been compiled, you use this new
type, in a main for example:
Person john;
Person jane;

• What you see above is just a declaration, no object


has been created yet

• All variables of an object type contain a reference,


not the object itself: just like we have seen for arrays
(and Strings too), because they are objects as well
22
Creating objects

Person john;
Person jane;

• When you have a reference that points nowhere, it


points to the special reference null

memory
john
null
null
jane
23
Creating objects
• To create an instance (an actual object), the basic
syntax is:
this calls the constructor!
Person john = new Person();
Person jane = new Person();

• This creates the object in memory, and returns a


reference (address) pointing to it memory

john name null


age 0

name null
jane age 0

24
Using the instance variables
• Given a reference to an object (e.g. john or jane
below), you can access the instance variables using
the syntax below, assuming that they are “public”
(but normally they shouldn’t be… more on that soon)

john.name = “John”;
jane.name = “Jane”;
john.age = 55;
jane.age = 42;
if (john.age > jane.age)
System.out.println(john.name + “ is older!”);

25
Instance methods
• Instance methods are methods that can only be used
on instances (instantiated objects)

• These methods have access to the instance variables


of that specific instance

26
Instance methods
• Instance methods are methods that can only be used
on instances (instantiated objects)

• These methods have access to the instance variables


of that specific instance

• They can be defined similarly to the methods we


introduced last week, but for instance methods you
must
• omit the static keyword
• add the public keyword (in most cases… more on
that soon)
27
Instance methods
• Example: See how the instance
methods refer directly to
public class Person{
the instance variables of
public String name; some specific object (a
public int age; specific instance)

//Instance methods below:


public void haveBirthday() { age++; }
public int getNbLettersInName() {
return name.length();
}
}
28
Using an instance method
• You use an instance method by applying it as an
operation to one particular object instance:

jane.haveBirthday();
john.haveBirthday();
int numLetters = jane.getNbLettersInName();

.
objectInstance instanceMethod();

29
Using an instance method
• You use an instance method by applying it as an
operation to one particular object instance:

jane.haveBirthday();
john.haveBirthday();
int numLetters = jane.getNbLettersInName();

.
objectInstance instanceMethod();

• The instance methods are called “on” a specific instance,


and they will be able to access/change the instance
variables (e.g. name/age) of this specific instance
30
Message terminology
• This is traditionally known as “sending a message to
an object”

• E.g. send the haveBirthday() message to the jane


object:

jane.haveBirthday();

31
Under the hood
• E.g. send the haveBirthday() message to the jane
object:

jane.haveBirthday();

• This acts as if this was happening (WARNING: NOT


the way to do this in Java):
haveBirthday(jane);
//in class def:
public void haveBrithday(Person this) { this.age++; }

32
Under the hood
• E.g. send the haveBirthday() message to the jane
object:

jane.haveBirthday();

• This acts as if this was happening (WARNING: NOT


the way to do this in Java):
… but there is an actual this
haveBirthday(jane); keyword in Java that acts this way!
//in class def:
public void haveBrithday(Person this) { this.age++; }

33
Scope and the this keyword
• In an instance method, if you have a local variable
(e.g. a parameter) with the same name as an
instance variable  the local one will be used

34
Scope and the this keyword
• In an instance method, if you have a local variable
(e.g. a parameter) with the same name as an
instance variable  the local one will be used

• You can use the keyword this to represent the


current instance of the object (the instance on which
the method was called)

35
Scope and the this keyword
• In an instance method, if you have a local variable
(e.g. a parameter) with the same name as an
instance variable  the local one will be used

• You can use the keyword this to represent the


current instance of the object (the instance on which
the method was called)

• this can be used to specify that you want to access


the instance variable for the object that the message
was sent to

36
Scope and the this keyword
• Example:

public void setAge (int age)


{
this.age = age; //this. is necessary to disambiguate
}

37
Scope and the this keyword
• Example:

public void setAge (int age)


{ Just age refers to the parameter in this context
this.age = age; //this. is necessary to disambiguate
}
age of the object
the instance method
was called on

38
Scope and the this keyword
• Example 2:

public void setSameAgeAs (Person other)


{
this.age = other.age; //this. is optional here
}

39
Scope and the this keyword
• Example 2:

public void setSameAgeAs (Person other)


{
this.age = other.age; //this. is optional here
}

There is no “conflict” here, nothing to disambiguate.


You can use this if you want, but it’s not necessary in
this case.

40
The toString() method
• toString() is a very useful instance method, which
you should always try to supply using this signature:

public String toString()

41
The toString() method
• toString() is a very useful instance method, which
you should always try to supply using this signature:

public String toString()

• This method is automatically called by Java to get a


String representation of your object (called when
printing or concatenation is needed with your
object)

42
The toString() method
• When you define your toString() method for your
object, you control how your object will be displayed
as a String

public String toString() {


return name + “(“ + age + “)”; //e.g. Jane (42)
}

43
The toString() method
• Once toString() is defined, you can now get readable
results from, for example:

System.out.println(jane + “ and ” + john);

44
The toString() method
• Note that there is always a toString() method  if
you don’t supply one, Java uses a default one

• However in most cases it will not give you a useful


String  try it!

45
Constructors
• A constructor is a special method that is used to
instantiate (create an instance of) an object

• We normally use it to initialize the instance variables

• We can also use to do any kind of processing that


needs to be done when the object is created (input,
output, calculations, creation of other objects,
initialization of GUI panels, etc.)

46
Constructors
• A constructor is a special case of an instance
method:
• no return type at all (not even void)
• it must have the exact same name as the class

• It’s run automatically when an object instance is


created (by new <ClassName>(…) )

47
Defining a constructor
• Syntax:

public Person(String name, int age)


{
//instructions to do during object instantiation
}

48
Defining a constructor
• Syntax:
public makes it accessible
outside of this class

public Person(String name, int age)


{
//instructions to do during object instantiation
}

49
Defining a constructor
• Syntax:
name of the constructor:
same as class name

public Person(String name, int age)


{
//instructions to do during object instantiation
}

50
Defining a constructor
• Syntax:
list of parameters, just
like a normal method

public Person(String name, int age)


{
//instructions to do during object instantiation
}

51
Defining a constructor
• Syntax:

public Person(String name, int age)


{
//instructions to do during object instantiation
}

• Although it’s possible to have a private constructor,


we normally make them public

52
Defining a constructor
• You can define multiple constructors, as long as they
have different signatures (lists of parameters)
public class Person{
public String name;
public int age;
public Person(){
name = “Newborn”;
age = 0; 2 different
} constructors
public Person(String name, int age){ with different
this.name = name; parameters
this.age = age;
}
}
53
Defining a constructor
• You can define multiple constructors, as long as they
have different signatures (lists of parameters)
public class Person{
public String name;
public int age;
public Person(){
name = “Newborn”;
age = 0;
}
Note: You could also
public Person(String n, int a){ use different
name = n; parameter names to
age = a; just avoid the
} conflicts, so that ‘this.’
} isn’t required
54
Constructing new objects
• If any constructors are supplied, the correct
parameters for one of them must be used when
creating an instance:

Person john = new Person("John", 29); //2nd one


Person newborn = new Person( ); //1st one
Person you = new Person(0); //error  this
//constructor does not exist!

55
Constructing new objects
• When a constructor does not initialize the instance
variables, they just keep their default value

• Default value depends on type, as seen before


(either 0, 0.0, false, '\0000', or null)

56
Default constructors
• A default constructor is provided by Java in case no
constructor is defined in a class

public NameOfTheClass() { }

• This default constructor does not do anything except


instantiating the object

57
Default constructors
• A default constructor is provided by Java in case no
constructor is defined in a class

public NameOfTheClass() { }

• This default constructor does not do anything except


instantiating the object

• Note that this default constructor disappears as soon


as one constructor is defined in the class (no matter
the list of parameters it uses)

58
Default constructors
• Example:
//in Person.java file: //in Test.java file
public class Person { public class Test{
public String name; public static void main (String[] args) {
public int age; Person p = new Person();
} }
}

59
Default constructors
• Example:
//in Person.java file: //in Test.java file
public class Person { public class Test{
public String name; public static void main (String[] args) {
public int age; Person p = new Person();
} }
}

• This compiles perfectly, no errors  default


constructor is there to instantiate the Person object

60
Default constructors
• Example 2:
//in Person.java file: //in Test.java file
public class Person { public class Test{
public String name; public static void main (String[] args) {
public int age; Person p = new Person();
}
public Person(String n, int i){
}
//statements here
}
}

61
Default constructors
• Example 2:
//in Person.java file: //in Test.java file
public class Person { public class Test{
public String name; public static void main (String[] args) {
public int age; Person p = new Person();
}
public Person(String n, int i){
}
//statements here
}
}

• This does not compile anymore  no default


constructor!
cannot find symbol constructor Person()
62
Access modifiers
• Each variable or method in a class can have 4 different
access modifiers, which affect their
visibility/accessibility:

• public
• private
• protected
• package-private

63
Access modifiers
• Each variable or method in a class can have 4 different
access modifiers, which affect their
visibility/accessibility:

• public We’ll just focus on these 2 for now


• private
• protected We’ll come back to these ones in a
• package-private few weeks; ignore these for now!

64
Access modifiers
• public: means any code, anywhere, can access or use it

• private: means only methods in this same class can


access or use it

65
Access modifiers
Rule of thumb:

• Use private for instance variables


• Objects should deal with their own data and
provide public methods for others to
access/modify it

• Use public for most instance methods (unless you


have a method that should only be used internally,
then you can use private)
• methods are (normally) supposed to be used by others

66
Principle of encapsulation
• Encapsulation is one of the main features of object-
oriented programming

• It’s the idea that you can restrict access to some of


the object’s fields, you can hide some information
from other classes that use the object

67
Principle of encapsulation
• Goal: protecting the internals, preventing other
classes from misusing the object

68
Principle of encapsulation
• Goal: protecting the internals, preventing other
classes from misusing the object

• As a result of using encapsulation:

• all code that can affect the object’s members is


local (to that specific class)

• code is more reliable, easier to debug, easier to


update and maintain

69
Principle of encapsulation
• If the instance variables are private, then we provide
“accessor” and “mutator” methods (get/set
methods) if needed:

private String name;



public String getName() { return name; } //accessor
public void setName(String newName) { //mutator
name = newName;
}

70
Why not just public?
• Suppose you use: public String name;

• You have Person objects throughout the U of M


student records system. ".name" is used in 6,328
different places in the code.

• Now, for some good reason, you must change to


public char[ ] name; //name is now a char array

• You now need to update the code to make it work…

71
Why not just public?
• That means: you need to find
and change 6,328 other
places in the system, in 219
other classes…

72
Why not just public?
• That means: you need to find
and change 6,328 other
places in the system, in 219
other classes…

• … and Steve wrote some of


them and he was fired in
2012 and nobody
understands his code because
he didn't use any comments

73
Why not just public?
• That means: you need to find
and change 6,328 other
places in the system, in 219
other classes…

• … and Steve wrote some of


them and he was fired in
2012 and nobody
understands his code because
he didn't use any comments,
and nothing is working and…

74
Why not just public?
• That means: you need to find
and change 6,328 other
places in the system, in 219
other classes…

• … and Steve wrote some of


them and he was fired in
2012 and nobody
understands his code because
he didn't use any comments,
and nothing is working and…

75
Why not just public?
• That means: you need to find
and change 6,328 other
places in the system, in 219
other classes…

• … and Steve wrote some of


them and he was fired in
2012 and nobody
understands his code because
he didn't use any comments,
and nothing is working and…

76
Why not just public?
• If it was private, you could just modify getName()
and setName() and that’s it

• Maintainability is by far the most important thing!

77
Class variables and methods
• You can create variables and methods which do not
refer to any one specific instance (e.g. one actual
Person object), but belong to the class as a whole

• We call those:
• class variables
• class methods

• To create them, we need to use the static keyword


(yes, the one we saw in the first week of classes 
finally we learn what it means!)

78
Class variables and methods
• Example:
public class Person{
//instance variables - one per object created
private String name;
private int age;

//class variable - only one for the whole class


private static int population = 0;

//class method - cannot be applied to an object


public static int census() { return population; }

//remember to add population++ to all constructors!


}
79
Class variables and methods
• Example:
public class Person{
//instance variables - one per object created
private String name;
private int age;

//class variable - only one for the whole class class variables are
private static int population = 0; initialized at the same
time they are declared
//class method - cannot be applied to an object
public static int census() { return population; }

//remember to add population++ to all constructors!


}
80
Class variables and methods
• Example:
//Constructor could look like this:
public Person(String n, int a)
{
name = n;
age = a;
population++;
}

81
Class variables and methods
Person class
• Example:
population 3
//Constructor could look like this:
public Person(String n, int a)
Person
{
name Fred
name = n;
age 21
age = a;
population++; Person
} name John
p1 age 40
In a main, somewhere else,
p2 Person
you create 3 objects of type
p3 name Mary
Person, and this is what you age 29
get in the memory:
82
Class variables and methods
• You can also have class constants  just add final:

public class Person{


//instance variables - one per object created
private String name;
private int age;

//class constant
public static final boolean NEEDS_TO_EAT = true;
}

83
Calling methods
• Instance (non-static) methods:
someObject.method(…)

• Class (static) methods:


ClassName.method(…)

• Any method from inside the same class:


method(…) //the same class is assumed
//It can either be static or not.
//Same as this.method(…) for instance methods
//Same as <ThisClass>.method for static methods

84
Calling methods
• Example, trying to call instance and class methods of
Person from a main in another class:

Person john = new Person(“John”, 55);

john.haveBirthday();

int totalNbPeople = Person.census();

85
Methods you have used
• System.out.println(...)
• System is a class (google "Java System class")
• out is a public static variable in that class
• Its type is PrintStream
• println is a public instance method in the
PrintStream class.
• You're sending a println message to the object
referred to by the static out variable in the
System class.

86
Methods you have used
• Math.sqrt(…) is a public static method in Math

• Math.PI is a public static constant in Math

• main is a public static void method in your class

87
Comparing objects
• Comparing Object variables using == or != is not
usually what you want to do

• It only compares the references

• It does not look inside the objects, to check if the


instance variables have the same values (which is
normally what you’re trying to do)

88
Comparing objects
• Standard methods for comparing the actual data
inside Objects:

• object1.equals(object2) //gives a boolean

• object1.compareTo(object2) //gives an int


• Gives a negative value if object1 is “smaller”
• Gives a positive value if object1 is “larger”
• Gives a zero if they are “equal”
• For Strings, this checks “alphabetical order”

89
Comparing objects
• Similarly to the toString() instance method, you
should write these methods for your own objects.
Other methods can use them.

• There are default ones, but they’re not useful.

90
Places to use objects
• You can use an object type anywhere you can use
any other type
• as a parameter to a method
• as the return type of a method
• as the elements of an array
• as an instance variable in another object
• etc. etc.

91
Places to use objects
• Just remember that it's always a reference to an
object that is passed/returned/stored/etc.

• This was done many times in COMP 1010 with


Strings and arrays (which are objects)

92

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy