Software Engineering I SENG201
Lecture 6 – Objects and encapsulation March 2, 2022
Copyright By PowCoder代写 加微信 powcoder
Previous lecture
1. Identifiers and data types 2. Declarations
3. Arithmetic operators
4. Strings in Java
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
Constructors – a special method
• Called automatically when object is created
– E.g.,GreetermyGreeter=newGreeter();
• Why do we need constructors?
– Code that is executed for all instances of a class – E.g.,Initialisepropertyvalues
• Constructors are often overloaded
public class Student {
Identifier of constructor(s) is name of class
return type
return type
private int yearOfBirth; private String fullName;
public Student() {
yearOfBirth = 2000; fullName = “n/a”;
public Student(int aYear, String aName) {
yearOfBirth = aYear;
fullName = aName;
public void printStudentData() {
// without constructor, properties // are initialized to default values
// first version of constructor
// overloaded constructor
// to print values of Student
System.out.println(“Year of birth: ” +yearOfBirth); System.out.println(“Full name: ” +fullName);
public static void main(String[] argv) {
Student s1 = new Student();
Student s2 = new Student(1985, “ ”);
s1.printStudentData();
s2.printStudentData();
How about “destructors”?
• When objects not used anymore
– E.g., references are lost, program ends – NoexplicitdestructorsinJava
– Claim: Destructors would provide code to free memory
– But: Java is garbage collected – regularly cleans up memory
– Memory is not the only resource
• Storage, server/network connection, device driver memory, etc. – Stillmayneedseparatemethod(s)tofreeresources
• Need to be called explicitly at the right time
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
Static variables – example 1
public class MyCounter {
private int objectCounter = 0;
public MyCounter() { objectCounter++; }
public void printCounterValue()
{ System.out.println(“The current value of objectCounter is ” + objectCounter); }
public static void main(String[] args) {
MyCounter c1 = new MyCounter(); System.out.println(“After creating c1:”); System.out.print(“For c1 – “); c1.printCounterValue();
MyCounter c2 = new MyCounter(); System.out.println(“After creating c2:”); System.out.print(“For c1 – “); c1.printCounterValue(); System.out.print(“For c2 – “); c2.printCounterValue();
MyCounter c3 = new MyCounter(); System.out.println(“After creating c3:”); System.out.print(“For c1 – “); c1.printCounterValue(); System.out.print(“For c2 – “); c2.printCounterValue(); System.out.print(“For c3 – “); c3.printCounterValue();
After creating c1:
For c1 – The current value of objectCounter is 1 After creating c2:
For c1 – The current value of objectCounter is 1 For c2 – The current value of objectCounter is 1 After creating c3:
For c1 – The current value of objectCounter is 1 For c2 – The current value of objectCounter is 1 For c3 – The current value of objectCounter is 1
What happened?
objectCounter = 1
-objectCounter: int
objectCounter = 1
objectCounter = 1
• 3 individual objects
• 3 independent objectCounter variables
Static variables and methods
• “One per class” instead of one per instance / object
• Do not need object to access static variables or methods
Static variables – example 2
public class MyStaticCounter {
private static int objectCounter = 0;
public MyStaticCounter(){ objectCounter++; }
public void printCounterValue()
{ System.out.println(“The current value of objectCounter is ” + objectCounter); }
public static void main(String[] args) {
MyStaticCounter c1 = new MyStaticCounter(); System.out.println(“After creating c1:”); System.out.print(“For c1 – “); c1.printCounterValue();
MyStaticCounter c2 = new MyStaticCounter();
System.out.println(“After creating c2:”);
System.out.print(“For c1 – “);
c1.printCounterValue();
System.out.print(“For c2 – “);
c2.printCounterValue();
MyStaticCounter c3 = new MyStaticCounter(); System.out.println(“After creating c3:”); System.out.print(“For c1 – “); c1.printCounterValue(); System.out.print(“For c2 – “); c2.printCounterValue(); System.out.print(“For c3 – “); c3.printCounterValue();
After creating c1:
For c1 – The current value of objectCounter is 1 After creating c2:
For c1 – The current value of objectCounter is 2 For c2 – The current value of objectCounter is 2 After creating c3:
For c1 – The current value of objectCounter is 3 For c2 – The current value of objectCounter is 3 For c3 – The current value of objectCounter is 3
What happened?
objectCounter
MyStaticCounter
-objectCounter: int
objectCounter
objectCounter = 3
objectCounter
• 3 individual objects
• 1 shared objectCounter variable
Example 3 (part 1)
• Compiler complains
• Cannot make a static reference to a non-static field!
• Also applies to calling non-static methods in static methods!
public class MyStaticExample {
private static int theStaticInstanceVariable = 42; private int nonStaticInstanceVariable = 42010;
public static void printMessage(String messageText) {
System.out.println(“=== MESSAGE ===”); System.out.println(messageText); System.out.println(theStaticInstanceVariable); System.out.println(nonStaticInstanceVariable); System.out.println(“=== END OF MESSAGE ===”);
public void printAnotherMessage(String messageText) {
System.out.println(“=== ANOTHER MESSAGE ===”); System.out.println(messageText); System.out.println(theStaticInstanceVariable); System.out.println(nonStaticInstanceVariable); System.out.println(“=== END OF ANOTHER MESSAGE ===”);
public static void main(String[] args) { // see next slide }
• Methods must have different names • Notdifferentiatedbasedonstatic
Example 3 (part 2)
public class MyStaticExample {
// see previous slide
public static void main(String[] args) {
System.out.print(“The value of the static variable is “); System.out.println(MyStaticExample.theStaticInstanceVariable);
MyStaticExample.printMessage(“I am called without an object!”);
MyStaticExample m1 = new MyStaticExample(); m1.printAnotherMessage(“I am called with an object!”);
System.out.println(m1.theStaticInstanceVariable); // compiler warning
• WARNING: static field should be accessed in a static way • Also applies to static methods
What happened?
MyStaticExample
-theStaticInstanceVariable: int
-nonStaticInstanceVariable: int
+printMessage(messageText: String): void +printAnotherMessage(messageText: String): void …
theStaticInstanceVariable
nonStaticInstanceVariable = 42010
printAnotherMessage(…)
theStaticInstanceVariable
nonStaticInstanceVariable = 42010
printAnotherMessage(…)
theStaticInstanceVariable = 42
printMessage(…)
Which object?
// class MyStaticExample (see previous slides)
public static void printMessage(String messageText) { …
System.out.println(theStaticInstanceVariable); System.out.println(nonStaticInstanceVariable); …
public static void main(String[] args) { …
MyStaticExample.printMessage(…); …
What is the problem?
theStaticInstanceVariable
nonStaticInstanceVariable = 42010
printAnotherMessage(…)
theStaticInstanceVariable
nonStaticInstanceVariable = 42010
printAnotherMessage(…)
theStaticInstanceVariable = 42
printMessage(…)
Static variables and methods – more details
• “One per class” instead of one per instance / object
– Do not necessarily need an object to access static data or methods
– Since no object: access using class name
• Static variables
– Typical use cases
• “Share” variables amongst instances of class (see previous example)
• Utility functionality (e.g., Integer.MAX_VALUE)
• Static methods
– Typical use cases
• Access shared variables (see previous example)
• Utility functionality (e.g., Math.abs(double a))
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
Class relationship: “dependency”
• Methods of “client” use variable or method of “server” class
• Generic “use” in UML
Properties
PostGradStudent
Properties
Organize multiple classes in packages
• Matchsourcefiledirectoryandpackagehierarchies • Follownamingconventions
package uc.sms;
public class PostGradStudent {
private int mYearOfBirth; private String mFullName;
PostGradStudent()
mYearOfBirth = 2000;
mFullName = “n/a”;
PostGradStudent(int aYear, String aFullName) {
mYearOfBirth = aYear;
mFullName = aFullName;
public void setStudentName(String aFullName) {
mFullName = aFullName;
import uc.sms.PostGradStudent;
public class Course {
private int maxStudents;
private int minStudents;
private PostGradStudent mClassRep;
public void addClassRep(PostGradStudent aClassRep) {
mClassRep = aClassRep;
public static void main(String[] argv) {
Course seng201 = new Course(); PostGradStudent p = new PostGradStudent(); p.setStudentName(” “); seng201.addClassRep(p);
Course PostGradStudent
Multiple classes – core principles in OO
• Cohesion
– Related to relationships of concepts within classes
– Classrepresentssingleconcept
– Properties and methods are strongly related
– Aim:highcohesion
• Coupling
– Related to relationships between classes
– Class depends on another class if it uses objects of another class
• As properties or as local objects in methods
– Minimize impact of system evolution
– Aim:lowcoupling
Example – cohesion
-courseCode: String -courseName: String -creditPoints: int -lecturerName: String -lecturerOffice: String
-courseCode: String -courseName: String -creditPoints: int -lecturer: Lecturer
Are lecturer name and office really related to course?
-name: String
-office: String
If anything related to lecturer changes, we don’t have to touch course
Lecturer can be used (re)used at other places in our program
Example – coupling
-classRep: PostGradStudent
-outline: CourseOutline
PostGradStudent
-course: Course
CourseOutline
-courseID: int
-learningOutcomes: String
-detailedDescription: String
-midTermTest: AssessmentItem
AssessmentItem
-name: String
-grade: StringString -detailedDescription: String -course: Course
Complexity, lack of reusability Potential unintended ripple effects Potential redundancies
*Dependencies can also be because of objects created in methods.
The art of object-oriented design
• How to achieve low coupling? – But some coupling is necessary
• How to achieve high cohesion? – Without going to the extreme
• Need to find balance between coupling and cohesion – Considerreusability,conceptualrelationship
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
Encapsulation
• “Everything” in Java is encapsulated
Data (properties)
Operations (methods)
• Control access to encapsulated elements
– Information hiding – only “public interface” available to users of class
• How do we achieve that?
– Visibility – we have seen this before
– public(+): Properties + methods used by objects of any other class
– private(-): Properties + methods only available to objects of this class
– protected(#): Properties + methods available in package, subclasses
– No visibility modifiers specified: Properties + methods available in package 29
Example – version 1
public class SMS { …
public void enrolStudent(Student s) { … }
public static void main(String[] argv) {
SMS mySMS = new SMS(); Student s = new Student(); s.yearOfBirth = 1998; mySMS.enrolStudent(s);
public class Student {
public int yearOfBirth; private String fullName;
public void setYear(int aYear) {
yearOfBirth = aYear;
public void setName(String aName) {
fullName = aName;
public int getYear(){return yearOfBirth;} public String getName(){return fullName;}
May lead to unintended change from “outside”
SMS Student
Example – version 2
public class SMS { …
public void enrolStudent(Student s) { … }
public static void main(String[] argv) {
SMS mySMS = new SMS(); Student s = new Student(); s.setYear(1998); mySMS.enrolStudent(s);
public class Student {
private int yearOfBirth; private String fullName;
public void setYear(int aYear) {
yearOfBirth = aYear;
public void setName(String aName) {
fullName = aName;
public int getYear(){return yearOfBirth;} public String getName(){return fullName;}
Better May include checks
Privacy principles
• Make properties (instance variables) private
– Prevents changing values, accidentally or deliberately
– Make values available via public getter (aka accessor) methods
– Values set by constructor, or public setter (aka mutator) methods
• Make everything private unless there is a good reason not to
– Simplify “client” interface (only a setter or getter)
– Changing internal implementation of class does not impact “client” class
Variables Methods (public) Declarations
Methods (private)
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
Cartoon of the day
Key lesson: Proper class design and encapsulation increase maintainability and reusability. Private properties, and getters and setters help achieve encapsulation.
A Java capsule keeps you healthy and can be a great supplement for developers – just like a vitamin pill for some
https://www.edureka.co/blog/object-oriented-programming/
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com