CSE100F
- By the end of this week, students should be able to:
- Differentiate between a class and an object.
- Draw a simple class diagram.
- Identify the states of multiple objects of the same class.
- Procedural Programming:
- Performs a set of instructions, then provides an output.
- Usually solves simple tasks (e.g., printing 5 numbers).
- Object-Oriented Programming:
- Considers classes and objects.
- Used for complex tasks.
- Entity (e.g., Student):
- Attributes/features:
- ID
- Name
- Behaviors/Methods:
- Coming to class
- Studying
- Blue Print:
- Class Object: Students
- ID
- Name
- Object: Car
- Colour
- Type
- Model
- Features for an Alarm Clock:
- Alarm time
- Sound level
- Colour
- Size
- Date and time
- Behavior:
- Make sounds
- Set an alarm
- Turn alarm on
- Turn alarm off
- Representing Classes:
- Use UML (Unified Modelling Language) class diagrams to sketch classes.
- UML provides standard diagrams for graphically representing structures and behaviors of object-oriented systems.
- Why Class Diagrams?
- Easy to draw and interpret.
- Universally understood by software engineering/IT professionals.
- General Layout of a UML Diagram for a Class:
- Three rectangle compartments:
- Class name
- Attributes
- Methods
- Example: AlarmClock
- Attributes:
- second
- minute
- hour
- alarmMinute
- alarmHour
- alarmStatus
- Methods:
- setTime()
- setAlarmTime()
- turnAlarmOn()
- turnAlarmOff()
- Object State:
- Determined by its value. If an alarm clock is in ideal state:
- If it's ringing, its state is changed.
- If it's not ringing but not set, it's changed.
- Values can be the same, but objects are still different.
- Not possible to list all attributes of a class; include attributes appropriate for the specific situation.
- Information Hiding/Encapsulation:
- Hiding information of code that is useless to the programmer or end-user.
- Don’t want to give all information to the end user.
- Information hiding or encapsulation: The property of providing a limited interface and hiding the details of an object.
- Inheritance:
- Allows a derived class to inherit attributes and methods of a base class.
- Facilitates hierarchical, parent-child relationships among objects.
- Example: Employees of an organization
- Common attributes: ID, name, address, phone numbers.
- Common methods: retrieve contact details.
- Different attributes: salary (full-time), hourly payment rate (part-time).
- Different methods: calculate weekly payments.
- Without inheritance, common features would have to be defined separately for each class.
- Purpose of inheritance:
- Record common features among objects.
- Account for their differences.
- Parent-child relationships in UML class diagrams are represented using an arrow.
- Validate a parent-child relationship using the 'IS-A' question.
- The relationships between users:
- Student
- Student ID
- Student name
- Coursework Students
- weighted average marks
- enrolling in subject ()
- Research students
- Research topic records
- Applying for grant ()
Toaster
- numberOfRacks
- rackSize
- darknessSetting
- rackStatus
- setDarknessSetting()
- getRackStatus()
- StartToasting()
- StoptoastingEarly()
Steps for designing a class:
- Identify the class.
- Identify attributes/features.
- Identify behaviors/methods.
- Sketch the UML Model.
- Consider these details to identify attributes for a Pop-Up Toaster:
- How many racks the toaster has?
- How many slices of bread can each rack hold?
- What is the darkness setting set to?
- Whether racks are up or down?
- Behavior of a pop-up toaster (operations):
- View darkness setting
- Change darkness setting
- Lower rack/start toasting
- View rack status
- Stop toasting
UML diagram should have 3 rectangle compartments: - First for the class name
- Second for attributes
- Third for methods
Please use camelCase notation if there is more than one word in the attribute or method name.
In today lectures, we have learned about:
the concepts of classes and objects
representing classes using UML class diagrams
the concepts of object states and behaviour
the concepts of abstraction and encapsulation
and
the basic concepts of inheritance. - Next lecture we will learn about more details related to class diagrams, specifically, how to associate multiple classes with each other and how to produce a class diagram given a problem description.
Week 2 objectives: - Determine classes, attributes, and relationships among classes given a problem description in natural language.
- Differentiate between degrees of association relationship.
- Identify the values of cardinalities for each association in a class diagram.
- Subject Support Sessions:
- Support students who are feeling left behind, direct students to appropriate services, and encourage students who are disengaged from the subject.
- Services provided:
- Group Sessions
- Email Discussion
- One-On-One assistance if required
- Subject Support Tutor: Rogue Lyons
- Consultation Sessions: 10-11am and 1-2pm Wednesdays
- Online through Zoom - Link on LMS
- Coding Hub Sessions:
- Additional help with their assignments, labs, and lecture contents.
- Semester 1 support will be available both face-to-face and online via Zoom from Week 2 (March 11th) onwards.
- The Coding Hub will support Java programming, Python programming, SQL/Databases, Web Development, R programming, and Cybersecurity, with Python programming, SQL/Databases, R programming, and Cybersecurity offered in blended learning mode.
- Relation between users and productInteraction = purchase, assigned to, enroll in•BlueprintTwo classesStudent: classSubject:
- classInteraction: enroll in•AssociationAn association is a type of relationship that links two or more instances of one or more classes:An association can have the following components:the name of the relationshipthe roles played by the participating objectsthe relationship multiplicitiesAssociation NameAssociation names should be included in yourUML diagram to assist with the ease ofinterpretation.We write the name of the association on top ofthe connecting line between the objects.Optionally, we can also include a directionindicator to show how the association nameshould be read.Associations: Reflexive andirreflexiveThere are two types of associations - those between objects of the sameclass, and those between objects of different classes. We can call the firsttype (same) reflexive associations, and the second type (different)irreflexive associations.•
Objects of same class → Reflexive association → Role labels neededObjects of different classes → Irreflexive association → No need forAssociation Name in Reflexive Associationsthe following information on the nature of the association in•
Also note that the line representing the association starts at the'Person' class and also ends at the 'Person' class, indicating the factthat there are no other classes involved in this association.The association name, i.e., 'parent of clearly indicates that the natureof the relationship between two Person objects are that of a parentand child.Role NameIn an association, every participating class plays a particular role.
For associations that involve two or more classes, the roles are clearand unambiguous.In Student-Subject example, The role of the Student class is torepresent a student who enrolls in a subject. Similarly, the role of theSubject class in the association is to represent the subject(s) thestudent(s) enroll in.Degree of AssociationsThe degree of an association is the number of roles inthat association.A binary relationship (of degree 2) is one that has tworoles for the participating objects to play. Similarly,a ternary relationship (of degree 3) has three roles.
The multiplicity on each side, has two numbers (or the '' characters)separated by two dots (..). The pair represents minimum andmaximum number of instances of that side, which can beassociated with one instance of the other sideMultiplicitiesConsider the 'parent of' association again.When it comes to reflexive associations, themultiplicities are associated with roles, since, thesame class is participating in the association, intwo roles.One child can have a minimum of O parent and amaximum of two. Hence, the '0..2' multiplicity onthe 'parent' role.One parent on the other hand, can have aminimum of O children and a maximum of many.Hence, the '0.. multiplicity on the 'child' role.
Aggregation (parent) and Student (child). Delete the Class andthe Students still exist.(parent) and Room(child). Rooms don't exist separate to a•Modelling using Class DiagramsNow that we have learned about different elements of a classdiagram, how do we go about modelling a class diagram from atextual problem description?To construct the class diagram for a problem description, we needto:Identify the classesDiscover the relationships among the classesDetermine the multiplicities of the associations.Identify the attributes and operations of the classesThere is NO particular algorithm for completing the above tasks.However, there are some guidelines, which may help us model theclass diagram in an easier wayModelling using Class DiagramsThe process of analysing a textual description ofa problem is known as textual analysis, and it isthe most used approach of modelling usingclass diagrams.When performing textual analysis, the followingguidelines may be handy:Studentphone library methods Attributes :Permit expirinFor this subject, you are NOT required to write any pseudocode for any of the assessments.
Week 3 Objectives: write an executable Java programwrite programs in Java that use arithmetic operationswrite programs in Java that use selection and repetition control statementsTopic 3_ ProgramProgramming in Java - A First LookGetting Started with Java ProgramsHow to Approach a Programming ProblemOur First Program in JavaComponents of our First Java ProgramVariables, and Primitive Data TypesArithmetic Operations in JavaControl Flow in JavaMethods in a Java ClassSummaryGetting Started with Java ProgramsWriting a very basic program in Java requires some understanding of classes and objects.Before we start writing code, let's think about how toapproach a programming problem in the first place.A more practical approach is to think about the problemfirst and draft an informal solution.In programming terms, the informal solution is referred toas pseudocode. Pseudocode is not actual code, rather it'sa flexible way to outline the solution of a problem in aFor this subject, you are NOT required to write any pseudocode for any of the assessments.The purpose of thischapter was to introduce you with the concept of pseudocode, if you are not already familiar, to add to your problemsolving skills
public class First JavaProgram{public static void main(String[] args){int number1 = 5;int number2 = 10;int sum = number1 + number2;System.out.println("The sum is: " + sum);}}
Every Java executable code must be part of a class.The class has to be written in its own Java file, whose name is exactly the same as the name of the class.• The keyword public specifies that anyone can access this class or create an object of this class.• The keyword class just specifies that it is a class in Java.Every executable class in Java must have a method named main.public static void main(String[] args)System.out.println("The sum is: " + sum);As you can see, there are several concepts that we have to cover a bit later in the subject. For now, the takeawayfrom this chapter is this:
• Whenever you want to run Java code, the code must be inside a class.• The class name and the filename must match.• The class must have a main() method whose declaration must be writtenin the exact same way as line 3 of our program in above.Identifiers in JavaIdentifiers in Java• The names of classes, methods and variables are known collectively as identifiers.• The rules for constructing a valid identifier are as follows:。 It must start with a letter or an underscore。 It can be followed by zero or more letters, underscores or digits
variable = expression;• An expression may be made up of values, variables, operators, and method calls. When a Java program isexecuted by JVM, it evaluates the value of the expression on the right hand side and assigns the value on theleft hand side.Java Primitive Data TypesJava Primitive Data Types-We will use mainly: int, double, char and boolean.Why?Two main reasons:(a) They are adequate for most purposes, and(b) Once, we master these data types, we can extend these knowledge and skills to the rest without difficulty.Mixing Numerical Types in JavaJava allows the mixing of byte, short, int, long, float, and double in arithmetic expressions.Ignoring all the types besides int and double, the rule regarding mixing numeric types is as followsJava does not allow us to assign a value of type double (wider range) to a variable of type int (narrower range).Then double value 8.5 will be converted to the int value 8, and assigned to variable n.In general, when using arithmetic operators in Java, it is important to remember the following:• The order in which the operators are evaluated in Java follows the mathematical rules of precedence andassociation.• Division in Java will produce integer value is both the operand of division are integers• We need to be careful when assigning values of one type to another type and pay attention to type compatibilityControl Flow in JavaWhen a Java program executes, there are 3 basic ways that a program knows which is the next line of code toexecute. The structures that determine the flow of control (from execution of one line to the next) are known ascontrol structures.The 3 major control structures of Java are:• SequenceInstructions are executed in the order they are written. This is the default flow of control.
Suppose we have a program that has a variable to store a student's mark. If the mark is greater than 79, theprogram prints a congratulatory message, otherwise the program prints a message wishing better luck for nexttime. Let's consider this program belowWe can use if statement by itself, without any associated else block. We can also use multi-way branching using ifelseif-else blocks, where we not only make a choice between two possible branches, rather we choose from a numberof possiblenbers.Let's have a look at while loops first. The general structure of a while loop is as follows:This is the initialisation construct. In a while loop, the initialisation occurs before the actual loop starts.• Given the above definition of the Student class, we cannot run the class by itself. To have an executable program wecan either,• write a main method in the Student class• write another class (in the same directory) to test the Student class methods that contains the main method.
In this book, we've taken our first look at a Java program. We should now know:• how to write a basic Java program using a class and a main method.• what the primitive data types are in Java• what the allowed arithmetic operations we can perform are• how we can manage flow of control using selection and repetition control structures in Java, and• what are methods in a Java class and how we can call them..Java Library ClassesString ClassWhen programming in Java, we have classes that are:•We can easily find out the above information using the Java officialdocumentation.
The String class is part of the Java standard library.What is a String?A string is a sequence of characters treated as a single entity.The characters can be a letter from the alphabet, a numeric digit,a whitespace (i.e., space, tab, etc.), or a special character.The characters in a string can be referred to by their positions,which are usually called indexes.The figure below shows the string "Hello!" and the indexes of itscharacters. Note that in Java, the index count always starts from O(not 1)
String literalsA string object, which is represented using a sequence of charactersbetween double quotes is also referred to as a string literal.Escape SequencesThe characters in a string literal can be letters, digits, punctuation marks, etcThey can also be special characters such as the newline character.We can represent such a special character using what is known as an escapesequence. An escape sequence begins with a backslash and represents asingle character. The escape sequence representing the newline characteris \n.Representation of Unicode Charactersusing escape sequenceWe can include the Unicode value of any character in a string.To do this, we just write the 4-digit hexadecimal Unicode value followingthe escape sequence \u. A Unicode character is treated as a singlecharacter within the string.Concatenation with other Data TypesJava also allows us to use the concatenation operator to concatenate astring and a primitive data type value.In this case, the primitive data type value will be converted int