Uploaded by mavnicholas8

CSC1016S All-Lectures Notes

advertisement
CSC1016S All-Lectures Notes
CSC1016S All-Lectures Notes
CSC1016SLectureNotes
CSC1016S Lecture 16
Topic: Assignment 6
Course: CSC1016S
Date: 25/08/2023
Professor/Speaker: Aslam Safla
Summary
Announcement
Assignment 5 due on Monday 10am and late submission due on Wednesday
Prac test 1 second sitting taking place next week in Scilab A, 40 minutes after
the quiz
Theory test 1 on Wednesday, make sure to sign up for a venue and have
Lockdown Browser installed on your laptop
Assignment 6 due on the 4th of September
Assignment 6: Class Declarations with Encapsulation
A continuation from assignment 5
Correct version of the CarPark class will be uploaded on Wednesday
The exact names of instance variables and any additional methods you might
add do not matter
Use exact signature for the required methods
Exercise 1
Look at the constructor to get an idea of what the definitions of the instance
variables should be
lowerBound() and upperBound() methods are 'get' methods which return
Duration values
includes() checks if duration is within the lower bound (inclusive) and the upper
bound (exclusive)
Time periods need to be adjacent, and lower limit is included and upper limit is
excluded
precedes() checks if this time precedes the other time period
adjacent() checks if time period is adjacent to the other time period
Exercise 2
Goes hand in hand with exercise 3
Store a time period and tariff in an adjacent order
Use TimePeriod and Cost as your instance variables
Exercise 2 will be manually marked
Exercise 3
Use constructor to identify what type of instance variables are to be included in
class
SIPP Lecture 05
Topic: Introduction to Values
Course: CSC1016S
Date: 24/08/2023
Professor/Speaker: Maria Keet
Summary
Teleology
Teleological theories give priority to "the good" over "the right"
They evaluate actions by the goal or consequences that they achieve.
Correct actions are those that produce the most good or optimise the
consequences of choices, E.g. Voltaire’s “best of all possible worlds”
Wrong actions are those that do not contribute to the good.
Action-Based Approaches
Ethical egoism : 'good/happiness' to self
Utilitarianism : 'good/happiness' to the most
Altruism : 'good/happiness' to the other
Ethical egoism
Egoism focuses on self-interest
Ethical egoism claims that it is necessary and sufficient for an action to be
morally right that it maximize one's self-interest.
“Does the action benefit me, as an individual, in any way?”
Utilitarianism
Utilitarianism embodies the notion of operating in the public interest rather
than for personal benefit.
An action is right if it maximises benefits over costs for all involved, everyone
counting equal
Altruism
Altruism
“A decision results in benefit for others, even at a cost to some”
an action is ethically right if it brings good consequences to others (even at the
cost to yourself)
Altruists choose to align their well-being with others — so they are happy when
others thrive, sad when others are suffering.
Utilitarianism vs. Deontology
In utilitarianism what makes an action right/wrong is outside the action
It’s the consequences that make it right/wrong
For deontologists:
It’s the principle inherent in the action
If the action done from a sense of duty &
If the principle can be universalised, then
the action is right
Ubuntu
Ubuntu means humanness/humanity in isiZulu
When we want to give high praise to someone we say, Yu, u nobuntu; ‘Hey, so
and-so has ubuntu’. Then you are generous, you are hospitable, you are
friendly and caring and compassionate. You share what you have.
“My humanity is caught up, is inextricably bound up in yours.”
I am, because we are; and since we are, therefore I am
Ubuntu as an Ethical or Moral Principle
Ubuntu morality:
An action is right just insofar as it promotes shared identity among people
grounded on good-will
An act is wrong to the extent that it fails to do so and tends to encourage
the opposites of division and ill-will.
What is data mining/knowledge discovery?
Data mining is a process of exploration and analysis of large quantities of data,
by automatic or semi-automatic means.
To discover meaningful patterns and rules.
Note: in many cases, the data was not collected primarily for the purpose of
data mining
Professional Responsibility
Two underlying issues (1/2)
(1) Problem of ‘many hands’:
Situation where multiple actors are involved in the development and
deployment of technologies, which makes it hard to identify who exactly
did what.
Negatively affects the process of assigning blame when a technological
accident occurs, as well as who to praise for its success
Two underlying issues (2/2)
(2) Trustworthy Software:
The enhancement of the overall software and systems culture, with the
objective that software should be designed, implemented and maintained
in a trustworthy manner
CSC1016 Lecture 15
Topic: Design and UML Class Diagram
Course: CSC1016S
Date: 23/08/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
Sign-ups for theory test 1 will be opening today, for both 5pm and 6pm sitting
Those who have unreliable laptops should sign up for scilab venue
There's a lecture on Friday
Student.java and UCT.java (uploaded to Amathuba)
Java requires a return statement for every non-void method
When instance variable and parameter are the same name, use this. to refer to
instance variable
Use this() to call another constructor
Printing an instance of a class (by name) calls the toString method by default
Shallow and Deep copy
To compare two instances, we create an equals() method
Code Sample
Student x = new Student("Paul", "Smith", 9876543);
Student y = new Student("Peter", "Smith", 9876543);
Student z = x;
x.equals(y) returns "Different" because the names are different
x.equals(z) returns "Same" because they are "pointing" to the same
instance in memory (this is called shallow copy)
Because x and z are "pointing" to the same instance in memory, if one is
changed, the other will "see" the change(i.e. both instance variables will be
changed, but they'll still be equal)
if we change y from"Peter" to "Paul", x.equals(y) will return "Same" because
both instances contain the same data, but x == y will return "Different"
because they are "pointing" to different instances in memory(this is called
deep copy)
A shallow copy is a copy of the reference pointer to the object, whereas a
deep copy is a copy of the object itself
Design and UML Diagrams
USES OF UML
as a sketch: to communicate aspects of system
forward design: doing UML before coding
backward design: doing UML after coding as documentation –
often done on whiteboard or paper
used to get rough selective ideas
as a blueprint: a complete design to be implemented
sometimes done with CASE (Computer-Aided Software Engineering)
tools
as a programming language: with the right tools, code can be autogenerated and executed from UML
only good if this is faster than coding in a "real" language
Autogenerator is used to convert UML diagrams to actual code
3 Most Important Diagrams for UML
Class diagrams
Object diagrams
Sequence diagrams
UML Class Diagram
Contains:
The classes in the OO system
Their fields and methods
Connections between methods
Does not contain:
Details of how the classes interact with each other
Algorithmic details; how a particular behavior is
implemented
CSC1016S Lecture 14
Topic: CSC1016S
Course: Chapter 4 - Defining Classes I
Date: 22/08/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
Sort out authentication for signing in to the lab computers, the lab test will not
be written on personal laptops
Information Hiding and Encapsulation
Encapsulation is sealing the class, which then prevents direct access into the
class code
Always make instance variables private, unless for special cases
Abstraction is the process of taking away or removing characteristics from
something in order to reduce it to a set of essential characteristics.
Encapsulation is a way to restrict the direct access to some components of an
object, so users cannot access state values for all of the variables of a particular
object
Encapsulation can be used to hide both data members and data functions or
methods associated with an instantiated class or object.
Mutator Methods can Return a boolean
Generally set (or mutator) methods are void
They can be used to return a boolean value (i.e return true when the value is set
successfully and false when it was not set)
Preconditions and Postconditions
The precondition of a method states what is assumed to be true when the
method is called
The postcondition of a method states what will be true after the method is
executed, as long as the precondition holds
Overloading
Overloading is when we have two or more methods in the same class have the
same method names but different signatures
Method overloading is possible only if the overloaded methods have different
signatures. It cannot be possible if the signature is same and only the return
type is different
Overloading and Automatic Type Conversion
Java will try automatic type conversion when it cannot find a method signature
that exactly matches a method invocation
You Can Not Overload Operators in Java
Default Variable Initialization
Class types are initialized to null
boolean types are initialized to false
Other primitive types are initializes to the zero of their type, i.e.
char = 'u000'
byte = short = int = long = 0
float = double = 0.0
Local variables are not automatically initialized
It is good practise to explicitly initialize instance variables in a constructor
Always start a new class with a no-argument constructor, which will prevent
Java from creatimng its own default no-argument constructor with its own
default values for the instance variables
StringTokenizer(Available on Amathuba )
DESIGN AND UML CLASS DIAGRAMS
UML - Unified Modeling Language
UML is used to design structure of different interaction of classes within project
Design Phase
Design: Specifying the structure of how a software system will be written and
function, without actually writing the complete interaction
A transition from "what" the system must do, to "how" the system will do it
How do we design classes?
Class identification from project spec'/ requirements:
nouns are potential classes, objects, fields
verbs are potential method or respossibilities of a class
CSC1016S Lecture 13
Topic: Chapter 4 - Defining Classes I
Course: CSC1016S
Date: 21/08/2023
Professor/Speaker: Aslam Safla
Summary
ANNOUNCEMENTS
Prac test 1 first sitting taking place this week, on the usual signed-up lab
sessions
Prac test will begin 15 minutes into the lab session
Hard copies and handwritten notes are allowed, but no electronic assistance
No need to create equals() and toString() methods unless stated
Theory test 1 coming up next week Wednesday (30th August) at 18h00
Chemistry students will write the theory test at 17h00
Test will be online (on Amathuba)
Everything up until the 30th will be included in the theory test
SIPP will not be included in the theory test 1, but it will be included for
theory test 2 and the Exam
Past papers will be uploaded soon
Constructors
The purpose of constructors is to get and set initial values of instance variables
For primitive types, use "==" for comparison
For String types, use equals() for comparison
It is a good practise to include the equals() and toString() methods in every
class
3 Key Principles Of OOP
Abstraction & Encapsulation
Inheritance
Polymorphism
The Fundamental Rule For Testing Methods
Every method should be tested in a program in which every other method in
the testing program has already been fully tested and debugged
Information Hiding and Encapsulation
Information Hiding is when a programme interacts with the use but the classcode contents of the program are hidden from the user(i.e User can use the
class, but can not access the code that runs it)
Abstraction is the concept of discarding details in order to avoid information
overload
An abstraction includes only :
Publicly defined variables
Comments
Headings of non-private methods
Public definitions
Encapsulation is when we seal the class into a single unit(class object),
which hides the implementation details
Public and Private
public allows the data of a class to can be accessed and altered by other classes
linked to it
private blocks access to the data of a class anywhere outside the class itself
In abstraction, private methods and variables are excluded
Instance variables should be private except for special cases
Most of the time methods are declared public
Accessor and Mutator Methods
Accessor gets (or accesses) the value of an instance variable
Mutator sets (or changes) the value of the instance variable
Provide set methods for non-static instance variables
5 Methods that all classes should have
Constructor
toString()
equals()
get (depends on program)
set (depends on program)
The set method can return a boolean instead of the normal void
When a variable is final, its value does not change
CODE SAMPLE
1 public class Student {//Class name
2 private String name; //Instance variables
3 private String surname;
4 private long idNumber;
5 public Student() { //no-argument constructor
6 this("abc", "xyz", 123); //the this() method refers to the constructor of the same
signature and initializes the instance variables with these default parameters}
7 public Student ( String name, String surname, long idNumber){//an
argument constructor to initialize the instance variables with variable parameters
8 this.name = name; //initializes the instance variable name using the
parameter 'name'
9 this.surname = surname;
10 this.idNumber = idNumber;}
//The mutator methods
11 public void setName( String name) { this.name=name;}
12 public void setSurname( String surname) { this.surname=surname;}
13 //The Accessor methods
14 public String getName() { return name;}
15 public String getSurname() { return surname;}
16 public long getIdNumber() { return idNumber;}
17 public boolean equals ( Student other){//Used to compare two instances of a
class object //Compare the unique identifiers first, if equal then proceed to other
comparisons, if not equal then conclude than the two instances of the class object
are not the same
18 if ( this.idNumber.equals( other.idNumber)) {
19 if ((name.equals(other.name) && (surname.equals(other.surname))){
20
return true;}
21 return false;}
22 return false;}
23 public String toString(){
24 return "name: "+name+", surname: "+surname+", ID: "+ idNumber;
25 }}
CSC1016S Lecture 12
Topic: Chapter 4
Course: CSC1016S
Date: 18/08/2023
Professor/Speaker: Aslam Safla
Summary
ANNOUNCEMENTS
Practical test 1 next week, during lab sessions
Test on creating classes and defining methods
Test will be written using the lab computers
No lab quizzes next week
ASSIGNMENT 5 INTRO
Exercise One
Creates a car-packing ticket
toString() method returns a string representation of the Ticket object in the
form Ticket [ id="ddddd", time="hh:mm:ss"]
Exercise Two
Creates a collection of all the Tickets created
Register initializes the tickets and keeps track of the number of tickets
Exercise Three
Creates a car-parking Simulator
UIDGenerator is used to generate ticket IDs\
Analyse the code snippets to get a clear understanding on how to go about
writing the code
THE equals() AND toString() METHODS
Sample Code 1
1 public class Student {//Class name
2 public String name; //Instance variables
3 public String surname;
4 public long idNumber;
5 public Student() { //no-argument constructor
6 this("abc", "xyz", "123"); //the this() method refers to the constructor of
the same signature and initializes the instance variables with these default
parameters}
7 public Student ( String name, String surname, long idNumber){//an
argument constructor to initialize the instance variables with variable
parameters
8 this.name = name; //initializes the instance variable name using the
parameter 'name'
9 this.surname = surname;
10 this.idNumber = idNumber;}
11 public boolean equals ( Student other){//Used to compare two instances
of a class object
12 //Compare the unique identifiers first, if equal then proceed to other
comparisons, if not equal then conclude than the two instances of the class
object are not the same
13 if ( this.idNumber.equals( other.idNumber)) { ...}
14 } //Code to be completed by Lecturer and uploaded on amathuba
SIPP Lecture 04
Topic: Introduction to values
Course: CSC1016S
Date: 17/08/2023
Professor/Speaker: Maria Keet
Summary
Terminology: Computer Ethics
Computer Ethics describes the field that examines ethical/moral issues
pertaining to computing and information technology
We use moral theories to know if a certain action is good, and why it it
Moral theory: a way of defining morality
There are multiple moral theories
They differ on the core from which you start reasoning toward whether
something is ethical or ‘good’; e.g.:
Divine command theory: X is good just because God commands it
Cultural relativism: an action is judged good (or bad) based only on the
standards that have been adopted by one’s society
Teleological (utilitarianism): the right decision what is good or desirable
(not the motivation behind it) is the one that causes the most happiness
Terminology: Moral agency
Determined by several entity innate conditions, three of which are commonly
agreed upon:
1.Causality: An agent can be held responsible if the ethically relevant result
is an outcome of its actions
2. Knowledge: An agent can be blamed for the result of its actions if it had
(or should have had) knowledge of the consequences of its actions
3. Choice: An agent can be blamed for the result if it had the liberty to
choose an alternative without greater harm for itself.
Implicitly, observers tend to exculpate agents if they did not possess full moral
agency, i.e., when at least one of the three criteria is absent
MORAL THEORIES
Cultural Relativism
Ethics is relative
What is right for me might not be right for you
There is (always has been) a good deal of diversity regarding right and
wrong
Moral beliefs change over time and in a given Society
Social Environment plays an important role in shaping moral ideals
Two Basic Versions of Ethics
Action-based theories: How should I act?
Virtue-based theories: What sort of person should I be?
Golden Rule (ethic of reciprocity)
Confucius said in The Analects:
己所不欲、勿施於人
Never impose on others what you would not choose for yourself
Christianity (The words of Jesus Christ who died for our sins)
“So in everything, do to others what you would have them do to you, for
this sums up the Law and the Prophets.” ~Matthew 7:12
Action-Based Approaches
Action-based theories focus entirely upon the actions that a person performs
Teleological theory (Greek telos, meaning "end" or "goal"):
What are the consequences?
When actions are judged morally right based upon their consequences
Deontological theory (Greek deon = That which is binding, needful, right,
proper.)
What is my duty?
When actions are judged morally right based upon how well they
conform to some set of rules
Categorical Imperative
1st Principle: “act only in accordance with that maxim through
which you can at the same time will that it become a universal
law.” (principle of universality)
2nd Principle (1797): “So act that you treat humanity, both in your
own person and in the person of every other human being, never
merely as a means, but always at the same time as an end”
e.g.: killing is wrong, slavery is wrong,
Has two branches:
Duties: What are one's duties?(ought to follow)
Rights: What are one's rights?(entitlement to that)
Deontology: Duty-based Ethics (Pluralism)
Seven basic moral duties that are binding on moral agents:
Fidelity: one ought to keep promises
Reparation: one ought to right the wrongs that one has inflicted on
others
Justice: one ought to distribute goods justly
Beneficence: one ought to improve the lot of others with respect to
virtue, intelligence, and happiness
Self-improvement: one ought to improve oneself with respect to virtue
and intelligence
Gratitude: one ought to exhibit gratitude when appropriate
Non-injury: one ought to avoid injury to others
Deontology: Rights-based Ethics
A right is an entitlement to something (Specified in, e.g., UDHR, SA
Constitution)
In Information Technology, e.g.:
The right to know
The right to privacy
The right to property
CSC1016S Lecture 11
Topic: Chapter 4 - Defining Classes I
Course: CSC1016S
Date: 16/08/2023
Professor/Speaker: Aslam Safla
Summary
ANNOUNCEMENTS
Next week lab sessions will be on practical test 1
The prac will be based on the basics of classes
Instance variables, methods and constructors will be included in the prac test
We'll be having Friday lessons starting this Friday( 18th)
CONSTRUCTORS
A constructor is called when creating an instance of a class (using new)
Methods can be invoked inside constructors
first action of a constructor is to create an instance of the class ( with instance
variables included)
One constructor can call on other constructors within its body
Include a No-Argument
When a class has no specified constructors included by the programmer,
Java will automatically create a default no-argument constructor
A no-argument constructor takes no arguments, peformes no
initialization, but allows the class object to be created
Always add a constructor to your programmes
Sample Code 1
1 public class Student {//Class name
2 public String name; //Instance variables
3 public String surname;
4 public long idNumber;
5 public Student() { //no-argument constructor
6 this("abc", "xyz", "123"); //the this() method refers to the constructor of
the same signature and initializes the instance variables with these default
parameters}
7 public Student ( String name, String surname, long idNumber){//an
argument constructor to initialize the instance variables with variable
parameters
8 this.name = name; //initializes the instance variable name using the
parameter 'name'
9 this.surname = surname;
10 this.idNumber = idNumber;}
11 }
Sample Code 2
1 public class UCT {
2 public static void main (String[] args) {
3 Student x = new Student();//Calls no-argument constructor and sets
default values for the instance variables
4 Student x = new Student ("Paul", "Smith", 957740);// calls argument
constructor and assigns the parameters to the instance variables
The this Keyword
The this method is used to refer to instance variables in the class
Can be used for one constructor to call another
Can be used to separate overloaded methods
The order of constructors and methods does not matter in a class
The Methods equals and toString
Java expects certain methods, such as the toString and equals method to
be in all, or almost all classes
The purpose of the equals() method is to compare two objects of one class,
to see if they are exactly the same or not ( returns boolean value)
'==' cannot be used to compare objects
The function of the toString() method is to return a string value that
represents the data in the object
Sample Codes
public boolean equals (className objectName){}
public String toString () {}
CSC1016S Lecture 10
Topic: Chapter 4 - Defining Classes I
Course: CSC1016S
Date: 15/08/2023
Professor/Speaker: Safla Aslam
Verse of the day: Jeremiah 29:11 For I know the plans I have for you,” declares the
LORD, “plans to prosper you and not to harm you, plans to give you hope and a
future.
Summary
ANNOUNCEMENTS
Only students who have signed up for the lab session will be able to write the
course tests
Only attend lab sessions on the lab day you have signed up for
DECLARING VARIABLES IN A FOR STATEMENT
Variables declared within the for statement parameter will only be accessible
within the body of the loop
PARAMETERS OF A PRIMITIVE TYPE
Parameters are a way of passing values to a method (i.e. parameters are the
input values of a method)
For each comma separated parameter, type declaration is necessary
e.g public double myMethod(int p1. int p2, double p3)
This method can take in 3 int arguments, but cannot take more than one
double (automatic type casting)
Java does not have default parameters, as in Python
call-by-value/pass-by-value principle simple states that if you change the
argument's value inside a method, the outside (or original) value of the variable
will not be affected
example:
int a=1,b=2,c=3
double result = myMethod (a,b,c){a=b+c}
// The original value of a, outside the method will not change, only the value
of a inside the method will be altered
One method can call another method inside its body
CONSTRUCTORS
A constructor is a special kind of method that is designed to initialize the
instance variables of an object
public ClassName(anyParameters){code}//structure of a constructor
A constructor must have the same name as the class it's in
A constructor has no type returned, not even void
Every single class has a constructor
99% of constructors are
Constructors are used to construct an instance of a class and allocate
memory for the object of a class
Constructors are typically overloaded
Overloading is when we have more than one method with the exact same name
but different signature (i.e. methods have same name but different parameters)
Method Signature is the combination of a method's name and its parameter list
A class cannot have two methods with the same signature
If we declare two methods with the same signature, compilation error is thrown
Method signature does not include the return type of a method.
example:
public void myMethod(int a, int b)
public void myMethod(double c, double d)
This program will not run if the parameters of both methods are integers or
any lesser type (i.e. the parameters should not be ambiguous)
A constructor is called when an object of a class is created (using new)
If a constructor is invoked again (using new), the first object is discarded and an
entirely new object is created
CSC1016S Lecture 09
Topic: Chapter 4 - Defining Classes I
Course: CSC1016
Date: 14/08/2023
Professor/Speaker: Safla Aslam
Summary
ANNOUNCEMENTS
Starting from this week, we'll be having Friday lectures from 11h00-11h45
(LS2A) and 12h00-12h45 (New Lecture Theatre)
Introductions to assignments will be done on the Friday lectures from now on
ASSIGNMENT 4 INTRO
Unit testing is the most basic form of testing methods
Question 1 deals with unit testing
Check how to use JUnit in JGRASP by following this pathway:
Amathuba>CSC1016S>OOP in Java>Section 4>Using JUnit in JGRASP
After configuring JUnit, check top tabs for 'create JUnit' and click it to start new
JUnit file
More to be discussed on Friday
CHAPTER 4
DEFINING CLASSES I
Instance Variables and Methods
public void myMethod(Parameter_goes_here)
public : type of method (public, protected, private etc.)
void : type of value returned (String, int, double etc.)
myMethod : name of method
In Java we have two types of methods. Namely the void method and nonvoid method
At the end of every non-void method, the return statement must be
included
We can have any number of conditional return statements, but only one
will be returned by the method
void methods have no return statements, they only execute the specified
action within the method body
The 'main' function is a void method
Local variable: A variable declared within a method (i.e. a variable that
exists only within a method, as opposed to instance variables)
Java does not have global variables
SIPP Lecture 03-10/08/2023
Topic: ICT4D,UCT4Peace & War and green/sustainable
computing
Course: CSC1016S
Date: 10/08/2023
Professor/Speaker: Prof. Maria Keet
Summary
ICT4D
The D stands for development and has a neutral use and a political connotation
Potential of ICT4D
Knowledge can be shared by one person to another without any loss
With ICT people can have access to more information, which leads to more
knowledge
ICT can be used in developing countries to extend the distribution of
knowledge resources(e.g giving people tablets instead of physical information
papers)
What is the Digital Divide
The gap between those who have access to information society and those
who are deprived of such access
Two aspects:
Global Digital Divide(international)-between countries
Local Digital Divide-between groups in a particular country
What causes the Digital Divide
Poor education and illiteracy
Disability
Location(rural-urban)
Gender
Race
Income level
Consequences of the Digital Divide
Cultural bias in the applications and contents
Poor digital infrastructure
Inappropriate computer equipment
How to bridge the Digital Divide
Provide sustainable solutions in under-serviced communities
Government policy will have to change to make ICT more accessible to
all
Leapfrogging in technological development is when new form of
technology is invented without having to follow the steps of previous form
of technology (giant leap that bypasses current technology development )
Universal Service and Universal Access
USAASA (Universal Service and Access Agency of South Africa)
Universal service is an old principle that all residents of a country
should have access to basic communications services (Formulated in
the 1930's in the USA for telephone services)
Is Universal Service enough
Cost of metered access
Lack of appropriate and accessible content
Effective use - The capacity and opportunity to successfully integrate ICTs
into the accomplishment of self and collaboratively identified goals
ICT4Peace
For peace-building efforts
Peacebuilding: Measures targeted to reduce the risk of conflict by
strengthening national capacities
Examples :
Communication a
Multilingualism and translations
ICT4War
Examples:
Propaganda
Autonomous Weapon Systems
SUSTAINABLE COMPUTING
Source of Pollution
Basics(IT in social):
User devices (PCs, servers, tablets, smart phones etc) costs electricity
Printing
Computer network infrastructure
Policies, practices, greed:
Trashware
Forced obsolescence
Perl and Python are the most polluting languages
Java, C, C++ and Rust are the least polluting languages
"Greenest" programming language is C
Contributing to the solution
Energy management:
Devices for demand-side control
Feeding solar back into the Net(management of distributed energy
generation)
Scheduling computing jobs based on electricity peak demand/downtime
CSC1016S Lecture 08-08/08/2023
Topic: Chapter 4-Defining Classes I
Course: aCSC1016S
Date: 08/08/2023
Professor/Speaker: Aslam Safla
Summary
ANNOUNCEMENTS
No quiz or lab sessions this week
If in need of assistance, tutors will be present in Scilab A&B during lab sessions
For loop is necessary for assignment 3
No lecture tomorrow
MORE ON ARRAYS
Arrays in Python are dynamic, and static in Java
Code sample:
int[] age ={2,12,1};//creates array with integer elements
age.length //has a value of 3
Array is an object
If a variable is not of a primitive data type, then it's an object
DEFINING CLASSES
INTRODUCTION
Every program is a class
All helping software consists of classes
All programmer-defined types are classes
Classes are central to Java
An object represents an entity in the real world(e.g Person, Student,Money,
Currency etc)
Class defines object, object defines entity
An object has a unique identity state(properties), and behaviour(actions)
The state consists of a set of data fields (also known as instance variables) with
their current values
The behaviour is defined by a set of methods
A CLASS IS A TYPE
A class determines the type of data that an object can contain as well as the
actions(methods) it can perform
Primitive type vs Class type
Primitive type variable can onlt store a single piece of data(e.g. int stores
integers, char stores characters, double stores real numbers only etc.)
Class type value or object can have multiple pieces of data(e.g Money can
store strings as well as doubles)
For a given object, each piece of data can hold a different value
Contents of a Class
Generally main method is the last method defined in the main class
Class contains instance variables and methods
A class is a reference type
The 'new' Operator
Is used to create the object and associate it with its variable name:
ClassName classVar = new ClassName();
First, the new operator reserves memory for classVar
Calls the constructor, which goes and initializes the variable by referring
classVar to the actual object(className())
Instance Variables and Methods
Code sample:
public void myMethod()//Heading
{//Code to perform some action and compute its value}
public void is not part of the method signature but part of the header
CSC1016S Lecture 07-07/08/2023
Topic: Chapter 3-Flow of Control in Java
Course: CSC1016S
Date: 07/08/2023
Professor/Speaker: Aslam Safla
Summary
Tomorrow's lecture will be both in-person and online on MS teams, link to be
sent prior to lecture
ASSIGNMENT 3
Due on Friday 7pm
Instance variable is created inside class but outside any method
Seller Class
Use Money class and Currency class for unit price
Class should only contain 6 lines
Make instance variables public
You don't initialize public instance variables
No method required in this class
N.B compile Seller class before using it
TestSeller Class
Asks user for details and assigns the input values to their corresponding Seller
variables
code sample:
Seller x = new Seller();//Creates Seller object for TestSeller class
x.ID = keyboard.nextLine();//Stores user ID to Seller ID variable
MarketPlace Class
Seller x = new Seller();//Requered statement in makeSeller() method
Array should contain all Seller variables
CHAPTER 3
LOOPS
When to use while instead of for loop?
When the number of iterations(loops) is not known(minimum number of
iterations is 0)
When to use for loop instead of while loop?
When the number of iterations is known
No else statement for while loops
Use break statement to end while loop
Use continue to end current iteration
Do-while loop does something first, then tests the condition
Do-while code structure:
do {
statement_1;
statement_2;
:
statement_n;
} while (Boolean_condition);//Note the semi-colon at the end of the while
statement
Add if statement before do statement to convert do-while to ordinary while
loop
ALGORITHM AND PSEUDOCODE
An algorithm is a set of precise instructions that lead to a solution
THE FOR LOOP
Similar to python but structured differently
Doesn't create a list but acts as a counter
For loop structure:
for (Initializing;boolean;update)
{body}//Initialize-test(true)-iterate-update
For loop example:
for(number = 100; number >= 0; number--)//Iterates 101 times, because 0 is
included
{System.out.println(number + " bottles on shelf");}
Output:
100 bottles on shelf
99 bottles on shelf
:
0 bottles on shelf
System.exit(0) ends program(use in exceptional cases only)
CSC1016S Lecture 06-02/08/2023
Topic: Chapter 2-Console Input and Output
Course: CSC1016S
Date: 02/08/2023
Professor/Speaker: Aslam Safla
Summary
BOOLEAN EXPRESSIONS
&& : and
||
!
: or
: negation
LOOPS
1)While loop code structure:
while(boolean//executes loop only when boolean value is true)
{statement(s)}
2)Do-while loop code structure:
do
{statement(s)}//executes this block, then proceeds to the loop
while(boolean//executes loop only when boolean value is true)
{statement(s)}
3)For loop code structure:
for (Initializing;boolean;update)
{statement(s)}
For loop example:
for(number = 100; number >= 0; number--)
{System.out.println(number + " bottles on shelf");}
Equivalent while loop example:
number = 100;
while(number >= 0)
{System.out.println(number + " bottles on shelf");
number --;}
Output for both codes:
100 bottles on shelf
99 bottles on shelf
:
0 bottles on shelf
When executing break statement, nearest enclosing loop or switch ends
When executing continue statement, current loop body iteration of the nearest
loop statement ends
The exit statement (System.exit(0)) will immediately end the program
INTRODUCTION TO ARRAYS
Creating an array:
Type[] var_name = new Type[n]//where n is the number of items or elements in
array
Example:
double[] score = new double[3];
score[0] = 80;
score[1] = 99.9;
score[2] = 85.5;
//This creates an array of 3 scores, starting at index 0
Results: score = {80; 99.9; 85.5}
SIPP Lecture 02-03/08/2023
Topic: Social Context
Course: CSC1016S
Date: 03/08/2023
Professor/Speaker: Prof. Maria Keet
Summary
GROWTH OF THE INTERNET
1980s: bulletin boards, UseNet groups, email
1990s: world wide web, then search engines, e-commerce, mobile phones,
PDAs
2000s: record/CD shops close (in Europe, USA), smart phones, iPhone &
Android
Effects of INFORMATION AND COMMUNICATION
TECHNOLOGY(ICT) Revolution
Disruptive effects on:
– Buying and selling
– Communication
– Access to knowledge
– Socializing and falling in love
– Crime
– Classroom
Effects:
– Globalization & Economics
– Privacy and surveillance
– How we think?
Digital Natives
People born in the digital networked era:
– Spend much of life online: with little distinction between offline (identity)
and online
(identities)
– Express, create and relate while mediated by technology
– Tendency to multitask, not successfully
– Different notions of privacy (and online information can come back to haunt
you)
Many studies show the negative impact of mobile phone, laptop and tablet use
in the classroom.
Not everything is positive about ICT:
Disruptive effects on jobs
Changing media landscape
ICTs to facilitate violence (e.g.: drones, surveillance, autonomous weapons
systems)
Human disposability and the fear of Artificial Intelligence (well, robots)
Recall pop-quiz question
Automatisation typically has the consequence of firing employees
profit is generated by under-paying employees; can’t do that with robots;
then if all is
roboticised, then there’s no profit to be gained from
that, yet capital needs profits to
perpetuate itself
Asimov’s laws of robotics
1. A robot may not injure a human being or, through inaction, allow a
human being to
come to harm.
2. A robot must obey the orders given it by human beings except where
such orders would
conflict with the First Law.
3. A robot must protect its own existence as long as such protection does
not conflict with
the First or Second Laws.
In that order….
SIPP Lecture 01-27/08/2023
Topic: Social Context
Course: CSC1016S
Date: 27/08/2023
Professor/Speaker: Prof. Maria Keet
Summary
Social Issues and Professional Practice (SIPP)
Introduces ethical issues of computing
Introduces the effects of ICT on society, privacy concerns, intellectual property
and open source software, ICT for development, and professional codes of
conduct in ICT
Analysing and formulating arguments about such topics.
In this unit, we'll be covering :
- key historical notes of computing
- current states of affair and hotly debated topics
- the notion of ICT for peace and development
Prescribed textbook: SIPPnotes (on Amathuba)
Other suggested textbook: Ethics and Technology: Controversies, Questions,
and Strategies for Ethical Computing (4th Ed) Herman T. Tavani
Read Chapter 1 of SIPPnotes
Check SIPP00-whatSIPPquiz-2023AT.pdf under Resource on CSC1016S
Amathuba
OVERVIEW
This block in CSC1016S is about the values that underlie your professional life
Analytical tools helps you with:
– Formulating your own position regarding x
– Having a constructive argument with someone
– Detect flaws in your own or someone else’s argument
– Understand when to agree to disagree, and why
Assignment 10 (Essay) is part of SIPP
ChatGPT, Bard, CodePilot and the like are not to used in this course
As technological advances continue to significantly impact the way we live and
work, the critical importance of social issues and professional practice continues
to increase; new computer-based products and venues pose ever more
challenging problems each year.
CSC1016S Lecture 05-01/08/2023
Topic: Chapter 2-Console Input and Output
Course: CSC1016S
Date: 01/08/2023
Professor/Speaker: Aslam Safla
Summary
DELIMITER
What is a delimiter? In Java, delimiters are the characters that split (separate)
the input values into tokens
Java allows us to define any characters as a delimiter
Java uses uses whitespace character as it's default delimiter
keyboard.useDelimiter('new delimiter')//changes the keyboard default delimiter
TEXT INPUT
The Scanner class can also be used to read from files on the disk
import java.io.FileInputStream and java.io.FileNot FoundException in addition to
the Scanner class
Try/catch code:
1 Scanner fileIn = null ; // initializes fileIn to empty
2 try { // Attempt to open the file
3
fileIn = new Scanner( new FileInputStream("PathToFile")); }
4 catch (FileNotFoundException e) { // If the file could not be found, this code is
executed
5
System.out.println("File not found.");
6
System.exit(0); } ... Code continues here
Code to read text file:
7 if (fileIn.hasNextLine()//checks if file is not blank, then returns boolean
value){
8
int num = fileIn.nextInt();//reads and stores next integer value
9
String word = fileIn.next();//reads and stores next string value
10
String sentence = fileIn.nextLine();//reads and stores the whole line
FLOW OF CONTROL
Java has 3 types of loops:
-for loop (same as in python)
-while loop (same as in python)
-do-while loop (executes a block of code first, then runs the loop)
THE SWITCH STATEMENT
Code structure:
Switch(Controlling_Expression){
case Case_Label_1:
{ Statement;break;//executes statement(s) and then exits out of the flow}
case Case_Label_2:
{Statement;break;}
:
case Case_Label_n:
{Statement;break;}
default:
{Default_Statement;break;}
If break statement is excluded, all cases will be execute
Example:
1 String letter = "H";
2 Switch(letter){
3 case "H":
4
System.out.println("Hello ");
5 case "Y":
6
System.out.println("Goodbye");
7 default:
8
System.out.println("World");
9
break;}
Output: Hello World
Code sample:
int max = (n1>n2)?n1:n2;//Compares the two numbers and stores the one that
is bigger
CSC1016S Lecture 04-31/07/2023
Topic: Chapter 2-Console Input and Output
Course: CSC1016S
Date: 31/07/2023
Professor/Speaker: Aslam Safla
Summary
Console-Where user interacts with the program(i.e. computer screen)
System.out.println(Argument) //used to output a string
Systemis the package, out is the class, and println() is the method
Only one argument is allowed in println(), and can only concatenate the
argument using "+"
The print() method is like println(), except that it does not end a line
Printf:
Print formatter
printf leaves cursor at the end of the same line
Can take any number of arguments (i.e. printf(String, Arg_1,Arg_2,...)
The code:
double price = 19.8;
System.out.print("$");
System.out.printf("%6.2f", price);
System.out.println(" each");
will output the line $ 19.80 each
The format string "%6.2f" indicates the following:
– End any text to be output and start the format specifier (%)
– Display up to 6 right-justified characters, pad fewer than six characters on the
left with blank spaces (i.e., field width is 6)
– Display exactly 2 digits after the decimal point (.2)
– Display a floating point number, and end the format specifier (i.e., the
conversion character
is f. Can also use other conversion characters, see
Chapter 2 slides for more info)
Right-justified (from right to left): "+"
Left-justified (from left to right) : "-"
Centre justified (from centre)
:"^"
%n indicates new line(\n)
Code that is "old fashioned" but too expensive to replace is called legacy code
pr
CONSOLE INPUT AND OUTPUT USING SCANNER CLASS
code sample:
1 import Java.util.Scanner; //imports the scanner class
2 public class String entry {
3 public static void main ( String [] args){
2 Scanner keyboard = new Scanner(System.in); //creates scanner object
3 System.out.println("Enter your name:");
4 String name = keyboard.next(); //Reads and stores single string of user input
5 System.out.println("Hello " + name); // concatenates string "Hello " with
variable 'name'
6 }}
code I/O:
Enter your name:
Marc
Hello Marc
Primitive types of input:
-keyboard.nextInt() //reads single integer value
-keyboard.nextLine() //reads entire line
-keyboard.nextDouble() //reads single double value
-keyboard.next() //reads single string value
-keyboard.nextFloat()//reads single floating point value
-keyboard.nextChar()//reads single character
-keyboard.nextShort()//reads single short value
-keyboard.nextLong()//reads single long value
Each instance of the variable will have a new value stored
CSC1016S Lecture 03 - 26/07/2023
Topic: Variables in Java
Course: CSC1016S
Date: 26/07/2023
Professor/Speaker: Aslam Safla
Summary
IDENTIFIERS :
The name of a variable
Cannot start with a digit
All characters must be letters, digits or underscores (_)
Case sensitive (rate RATE Rate are all seen as different variables)
Reserved words are predefined words used for specific purposes in the Java
language and cannot be used for naming.
Predefined identifiers are defined in libraries required by the Java language
standard
Valid names:
○x
○ x1
○ x_1
○ _abc
○ ABC123
○ sum
○ data2
○ bigBonus
● Invalid names :
○ 12
○ 3X
○ %change
○ data-1
○ myfirst.java
○ PROG.CLASS
Camelcase (topSpeed, timeOfArrival, bankRate1)
Variable names typically begin with a lowercase letter
Constant variable are all uppercase (GRAVITY = 9.8) (their values do not
change)
Use descriptive names (no var1, var2 please)
Class names start with an uppercase letter (FirstProgram)
VARIABLES:
Every variable must be declared before it can be used
The basic types in Java are called primitive types:
byte>short>int>long>float>double
When a variable is declare you are telling the compiler what data will be stored
in it
○ int numberOfBeans;
○ Double oneWeight, totalWeight;
○ String userName;
"=" is the assignment operator (i.e numberOfBeans = 15;)
ARITHMETICS:
+ : Addition
- : Subtraction
/ : Division
* : Multiplication
% : Modulus(Remainder)
++ : Increment
-- : Decrement
Type Casting:
A type cast takes a value of one type and produces a value of another type
This value is Java’s best guess of an equivalent value
This expression is a type cast:
○ (double)m
○ m is an integer
○ If m was 2 them after the type cast it is 2.0
Increment and Decrement Operators:
Increment operator (++) adds one
Decrement operator (--) subtracts one
n++ //Uses the value n, and after increments n by 1
++n //Increments n by 1, then uses the new value instead
ESCAPE SEQUENCES:
\" : Double quote
\'
\\
\n
\r
\t
: Single quote
: Backslash
: Newline
: Carriage return
: Tab
CSC1016S Lecture 02 - 25/07/2023
Topic: Introduction to Java
Course: CSC1016S
Date: 25/07/2023
Professor/Speaker: Aslam Safla
INTRODUCTION TO JAVA
Java is an Object-Oriented Program (OOP)
Created by James Gosling (in 1991)
Released by Sun Microsystems (in 1996)
A type of Interpreted language (executes one line at a time)
Functions are called methods in Java
Java is a compiled language
A regular Java program is a class with the main method
JAVA CODING STEPS: Java code/java byte code/machine language/execute
Java can be considered both a compiled and an interpreted language because
its source code is first compiled into a binary byte-code. This byte-code runs on
the Java Virtual Machine (JVM), which is usually a software-based interpreter.
Why Java byte code?
Makes Java portable
Allows program to run across various machines
Difference between compiled and interpreted language:
A compiled language is converted into machine code so that the processor
can execute it.
An interpreted language is a language in which the
implementations execute instructions
directly(line by line) without
earlier compiling a program into machine language. The
compiled
programs run faster .t
A Simple Java Program
● A java program is a class definition with a method named main
● When the program is run the actions specified in main are carried out
● The body of the method is enclosed in curly braces {}
○ Everything that the program is going to run needs to be inside of them
● public static void main(String[] args)
TYPICAL HELLOWORD PROGRAM
1 public class FirstProgram //class name
2{
3
public static void main ( String [ ] args) //main method
4
{
5
System.out.println("Hello world");
6
//Semi-colons at the end of every statement
7
}
8}
OUTPUT : Hello world
CSC1016S Lecture 01 - 24/07/2023
Topic: Introduction to students
Course: CSC1016S
Date: 24/07/2023
Professor/Speaker: Aslam Safla
Summary
Java lessons from Monday to Wednesday (by Mr. Aslam
Saflaaslam@cs.uct.ac.za )
SIPP lessons on Thursdays (by Prof. Maria Keet mkeet@cs.uct.ac.za )
Friday lessons are on only when necessary (TBA)
Recommended textbook : Absolute Java, (International/Fifth edition or later) by
Walter Savitch, Pearson / AddisonWesley, ISBN: 9780273764793
SIPP textbook available on Amathuba website
2 practical tests and 2 theory tests (all compulsory)
SIPP essay assignment is compulsory
CSC1016S All Lecture Notes
CSC1016S Lecture 26
Topic: CHAPTER 8 - POLYMORPHISM AND ABSTRACT
CLASSES
Course: CSC1016S
Date: 20/09/2023
Professor/Speaker: Aslam Safla
Verse of the day: Matthew 11:28 -30
“Come to me, all you who are weary and burdened, and I will give you rest. 29 Take
my yoke upon you and learn from me, for I am gentle and humble in heart, and you
will find rest for your souls. 30 For my yoke is easy and my burden is light.”
Summary
ANNOUNCEMENTS
This week Friday's lecture is going to be a very important one
Friday's lecture is Aslam's very last lecture
Introduction to Polymorphism
Polymorphism is the ability to associate many meanings to one method name
It does this through a special mechanism known as late binding or dynamic
binding
Inheritance allows a base class to be defined, and other classes derived from it
Code for the base class can then be used for its own objects, as well as
objects of any derived classes
Polymorphism allows changes to be made to method definitions in the derived
classes, and have those changes apply to the software written for the base class
Late Binding
The process of associating a method definition with a method invocation is
called binding
If the method definition is associated with its invocation when the code is
compiled, that is called early binding
If the method definition is associated with its invocation when the method is
invoked (at run time), that is called late binding or dynamic binding
Java uses late binding for all methods (except private, final, and static methods)
Because of late binding, a method can be written in a base class to perform a
task, even if portions of that task aren't yet defined
Pitfall: No Late Binding for Static Methods
When the decision of which definition of a method to use is made at compile
time, that is called static binding
This decision is made based on the type of the variable naming the object
Java uses static, not late, binding with private, final, and static methods
In the case of private and final methods, late binding would serve no
purpose
However, in the case of a static method invoked using a calling object, it
does make a difference
The final Modifier
A method marked final indicates that it cannot be overridden with a new
definition in a derived class
If final, the compiler can use early binding with the method
public final void someMethod() { . . . }
A class marked final indicates that it cannot be used as a base class from which
to derive any other classes
Upcasting and Downcasting
Upcasting is when an object of a derived class is assigned to a variable of a base
class (or any ancestor class)
Downcasting is when a type cast is performed from a base class to a derived
class (or from any ancestor class to any descendent class)
Downcasting has to be done very carefully
In many cases it doesn't make sense, or is illegal:
CSC1016S Lecture 24
Topic: Chapter
Course: CSC1016S
Date: 18/09/2023
Professor/Speaker: Aslam Safla
Summary
Quiz 5 taking place this week
Prac test 1 final sitting taking place this week after quiz
No need for signup
Submit prac test code even if it doesn't work 100%
All sample codes have been uploaded on Amathuba csc1016s resources
Derived Class(Subclass)
Derived class does not have direct access to private instance variables and
methods
Derived class can only access private instance variables through get and set
methods
Inherited Members
A derived class automatically has all the instance variables, all the static
variables, and all the public methods of the base class
Members from the base class are said to be inherited
Definitions for the inherited variables and methods do not appear in the
derived class
The code is reused without having to explicitly copy it, unless the creator of
the derived class redefines one or more of the base class methods
Overriding a Method Definition
Although a derived class inherits methods from the base class, it can change or
override an inherited method if necessary
In order to override a method definition, a new definition of the method is
simply placed in the class definition, just like any other method that is
added to the derived class
example, toString() and equals()
Changing the Return Type of an Overridden Method
Ordinarily, the type returned may not be changed when overriding a method
However, if it is a class type, then the returned type may be changed to that of
any descendent class of the returned type
This is known as a covariant return type
Changing the Access Permission of an Overridden Method
The access permission of an overridden method can be changed from private in
the base class to public (or some other more permissive access) in the derived
class
However, the access permission of an overridden method can not be changed
from public in the base class to a more restricted access permission in the
derived class
Pitfall: Overriding Versus Overloading
Do not confuse overriding a method in a derived class with overloading a
method name
When a method is overridden, the new method definition given in the
derived class has the exact same number and types of parameters as in the
base class
When a method in a derived class has a different signature from the
method in the base class, that is overloading
Note that when the derived class overloads the original method, it still
inherits the original method from the base class as well
For child class to access a visible accessible overridden method from parent
class use super()
The final Modifier
If the modifier final is placed before the definition of a method, then that
method may not be redefined in a derived class
It the modifier final is placed before the definition of a class, then that class may
not be used as a base class to derive other classes
The super Constructor
A derived class uses a constructor from the base class to initialize all the data
inherited from the base class
In order to invoke a constructor from the base class, it uses a special syntax:
public derivedClass(int p1, int p2, double p3)
{
super(p1, p2);//must always start by calling the super constructor
instanceVariable = p3;//this child class has p3 as its only instance variable
}
In the above example, super(p1, p2); is a call to the base class constructor
A call to the base class constructor can never use the name of the base class,
but uses the keyword super instead
A call to super must always be the first action taken in a constructor definition
An instance variable cannot be used as an argument to super
If a derived class constructor does not include an invocation of super, then the
no-argument constructor of the base class will automatically be invoked
This can result in an error if the base class has not defined a no-argument
constructor
Since the inherited instance variables should be initialized, and the base class
constructor is designed to do that, then an explicit call to super should always
be used
The this Constructor
Within the definition of a constructor for a class, this can be used as a name for
invoking another constructor in the same class
The same restrictions on how to use a call to super apply to the this
constructor
If it is necessary to include a call to both super and this, the call using this must
be made first, and then the constructor that is called must call super as its first
action
• Often, a no-argument constructor uses this to invoke an explicit-value
constructor
No-argument constructor (invokes explicit-value constructor using this and
default arguments)
Tip: An Object of a Derived Class Has More than One Type
An object of a derived class has the type of the derived class, and it also has the
type of the base class
More generally, an object of a derived class has the type of every one of its
ancestor classes
Therefore, an object of a derived class can be assigned to a variable of any
ancestor type
An object of a derived class can be plugged in as a parameter in place of any of
its ancestor classes
In fact, a derived class object can be used anyplace that an object of any of its
ancestor types can be used
Note, however, that this relationship does not go the other way
An ancestor type can never be used in place of one of its derived types
Pitfall: The Terms "Subclass" and "Superclass"
The terms subclass and superclass are sometimes mistakenly reversed
A superclass or base class is more general and inclusive, but less complex
A subclass or derived class is more specialized, less inclusive, and more
complex
As more instance variables and methods are added, the number of objects that
can satisfy the class definition becomes more restricted
instanceOf(classType) checks what type a specific class is of and returns either
true or falsee depending on the parameter type
SIPP Lecture 12
Topic: Intellectual Property
Course: CSC1016S
Date: 19/10/2023
Professor/Speaker: Maria Keet
Verse of the day:"Revelation 22:12 And behold, I come quickly and my reward is with
me, to give to every man according as his work shall be,"
Summary
Lesser GPL (aka GNU Library)
GPL says you are free to modify software and combine it with other libraries,
but that all such extensions must also be distributed under GPL
GNU Library or Lesser GPL has less stringent conditions
Allows open-source libraries to be used in proprietary applications
The Creative Commons(CC)
The Creative Commons (CC), a nonprofit organization, was lunched by
Lawrence Lessig and others in 2001
CC aims at providing creative solutions to problems that currently copyright
laws pose for sharing information
Creative Commons: Key Themes
Minimum of fuss creativity:
Sharing, Accessing, Collaborating and Negotiating
Unleash the potential of the digital environment
Free Culture-Free to Access
a repository of open space or commons
Not anti-copyright
Relies on and is complementary to copyright
Four main protocols
Attribution: Other people may use, modify and distribute the work, as long as
they give the original author credit
Non-commercial: Other people may use, modify and distribute the work, but
for non-commercial purposes only
No derivatives: Other people may use and distribute the work, but can not
modify it to create derivative works
Share alike: Other people may modify the work and distribute derivatives, but
only on the condition that the derivatives are made available to other people
on the same licence
This term can not be used with the No derivatives term, because it applies
only to derivative works
Conclusion
Open Source is clearly a phenomenon which has and will continue to greatly
impact software use and development
Open Source and proprietary software are likely to coexist for some time
Many traditional software companies are adopting some "open source"
practices and principle
Open Source has reached mainstream acceptance, with an increasing
number of organizations and companies, promoting, developing and using
open source software
People are generalizing the idea beyond just software to other forms of digital
content.
CSC1016S Lecture 40
Topic: Chapter 17: GUI with Java Swing Part 2
Course: CSC1016S
Date: 18/10/2023
Professor/Speaker: Francois Meyer
Summary
Announcements
This is the last Java lecture
Friday lecture will be code demo
Monday is the very lecture-Aslam will be briefing on the coming Exam
GUI COMPONENTS
Swing
A text field is an object of the class JTextField. It allows the user to enter a single
line of text.
JTextField in = new JTextField("Enter name", 30);
String inputString = in.getText();
in.setText("");
A text area is an object of the class JTextArea. It is the same as a text field,
except that it allows multiple lines
A menu is an object of the class JMenu. A choice on a menu is called a menu
item, and is an object of the class JMenuItem.
JMenu sortMenu = new JMenu("Sort by");
JMenuItem recent = new JMenuItem("Recent");
recent.addActionListener(new ItemListener());
sortMenu.add(recent);
JMenuItem likes = new JMenuItem("Most likes");
likes.addActionListener(new ItemListener());
sortMenu.add(likes);
A menu bar is a container for menus, typically placed near the top of a
windowing interface.
JMenuBar bar = new JMenuBar();
bar.add(sortMenu);
LAYOUT MANAGERS
Swing
Containers vs Components
1. Any class that is a descendent class of the class Container is considered
to be a container class. e.g. JFrame, JPanel
2. Any container object can have components added to it. Any descendent
class of the class JComponent is called a component class. e.g. JButton,
JLabel, JTextField, JTextArea
Almost every GUI built using Swing container classes will be made up of three
kinds of objects:
1. The container itself, probably a panel or window-like object.
2. The components added to the container such as labels, buttons, and
panels.
3. A layout manager to position the components inside the container.
The add method adds components to a JFrame, but doesn’t specify how they
are arranged.
To describe how multiple components are to be arranged, a layout manager is
used.
There are a number of layout manager classes:
BorderLayout (default)
FlowLayout
GridLayout
To add a layout manager to a JFrame:
setLayout(new BorderLayout());
A BorderLayout manager places the components that are added to a JFrame
object into 5 regions.
FlowLayout manager is the simplest layout manager.
It arranges components one after the other, going from left to right, in the
order in which they are added.
GridLayout arranges components in a 2D grid with some number of rows and
columns.
setLayout(new GridLayout(rows, columns));
Each entry is the same size.
Each component is stretched so that it fills its grid position.
Items are placed in the grid from left to right, top to bottom
GridLayout arranges components in a 2D grid with some number of rows and
columns.
setLayout(new GridLayout(rows, columns));
Creates a grid with specified number of rows and as many columns as
required.
setLayout(new GridLayout(rows, 0));
Same!
setLayout(new GridLayout(0, columns));
Creates a grid with specified number of columns and as many rows as
required.
A GUI is often organized in a hierarchical fashion, with containers called panels
inside other containers.
A panel is an object of the JPanel class that is a simple container.
It subdivides a JFrame and groups smaller objects into a larger components
(e.g. buttons into a panel, panels into a JFrame).
A JFrame and each panel in it can use different layout managers.
=⇒ Enables almost any kind of overall layout to be used in a GUI.
(Panels within the JFrame, panels within those panels, etc.)
ACTION COMMANDS
Swing
When a user clicks a button or menu item, an event is fired that normally goes
to one or more action listeners.
This action event includes a String instance variable called the action
command for the button or menu item.
This string can be retrieved with e.getActionCommand().
JButton nextButton1 = new JButton("NEXT");
next1.setActionCommand("next1");
JButton nextButton2 = new JButton("NEXT");
next2.setActionCommand("next2");
The default value for the action command string is what’s written on the button
or the menu item.
The setActionCommand method can be used to change the action command
for a component (useful when multiple components have the same default
action command.
CSC1016S Lecture 39
Topic:Chapter 17: GUI with Java Swing
Course:CSC1016S
Date: 17/10/2023
Professor/Speaker: Francois Meyer
Summary
GUI: Graphical User Interface
Is a windowing system that interacts with the user.
In Java, the AWT (Abstract Window Toolkit) package was the original Java
package for creating GUIs.
The Swing package is an improved version of AWT.
Some AWT classes are replaced by Swing classes, but other AWT classes are
needed when using Swing
Event-driven programming
Event-driven programming is a programming style that uses a signal-andresponse approach to programming
Flow of the program is determined by events such as user actions (mouse
clicks, key presses).
How does Event-driven programming work?
Windows contain GUI components e.g. buttons.
These send events to other objects called listeners.
An event is an object that acts as a signal to a listener.
The sending of an event is called firing the event.
e.g. When a button is clicked, it fires an event that sends a signal to another
object, telling that object what to do.
What is a listener?
A listener object performs some action in response to the event.
e.g. When a login button is clicked, check if the entered username and
password is correct.
A component may have several listeners.
Each listener may respond to a different kind of event, or multiple listeners
might may respond to the same events.
What is an event handler?
Methods that specify what happens when events occur.
A listener object has methods (event handlers) that specify what happens
when events of various kinds are received by it.
e.g. When a login button is clicked, check if the entered username and
password is correct.
The programmer using the listener object will define or redefine these
event-handler methods.
Swing
A simple window can consist of an object of the JFrame class.
1. The JFrame class is found in the javax.swing package
JFrame firstWindow = new JFrame();
2. A JFrame object includes a border and the usual three buttons for
minimizing, changing the size of, and closing the window.
3. A JFrame can have components added to it, such as buttons, menus, and
text labels.
firstWindow.add(endButton);
firstWindow.setVisible(true);
GUI components are available as Swing classes. They can be added to the
window.
A button object is created from the class JButton.
JButton button1 = new JButton("Click");
firstWindow.add(button1);
Text can be added to a JFrame using a label.
JLabel label1 = new JLabel("Hello");
firstWindow.add(label1);
A color is an object of the class Color from the java.awt package.
There are constants in the Color class that represent a number of basic
colors.
The background color of a JFrame can be set:
getContentPane().setBackground(Color.BLUE);
The color of a GUI component can also be set:
button1.setBackground(Color.PINK);
A pixel is the smallest unit of space on a screen.
The size and position of Swing objects are measured in pixels.
A screen’s resolution is the number of pixels it uses to display.
For a fixed size screen...
High resolution: many pixels, windows will look smaller.
Low resolution: fewer pixels, windows will look larger.
GUI programs are often based on a kind of infinite loop.
The windowing system normally stays on the screen until the user indicates
that it should go away.
In order to end a GUI program, System.exit must be used when the user
asks to end the program.
It must be explicitly invoked, or included in some library code that is
executed. Otherwise, a Swing program will not end.
Listeners
A button object is created from the class JButton.
JButton button1 = new JButton("Click");
firstWindow.add(button1);
In order to let this button do something:
Specify what objects are its listeners, i.e. register listeners.
Define the methods that will be invoked automatically when the event is
sent to the listener.
A button object is created from the class JButton.
JButton button1 = new JButton("Click");
firstWindow.add(button1);
EndingListener buttonEar = new EndingListener();
button1.addActionListener(buttonEar);
A listener object named buttonEar is created and registered as a listener for the
button named button1.
Buttons fire events known as action events, which are handled by listeners
known as action listeners.
Different kinds of components require different kinds of listener classes to
handle the events they fire.
An action listener is an object whose class implements the ActionListener
interface.
ActionListener has one method to be implemented.
public void actionPerformed(ActionEvent e)
When the user clicks a button, an action event is sent to the action listener
for that button.
The action listener receives the action event as the parameter e to its
actionPerformed method (automatically invoked).
Note that parameter e must be received, even if it is not used.
CSC1016S Lecture 38
Topic: Chapter 15: Stacks & Queues
Course: CSC1016S
Date: 16/10/2023
Professor/Speaker: Francois Meyer
Summary
Stacks & Queues
What are stacks and queues in Computer Science?
Data structures that operate in specific ways regarding adding and
removing data.
They are used in many different settings (well known data structures in
computing).
They can be implemented as linked lists.
Stacks and queues are not necessarily linked data structures (can be
implemented in other ways too).
Stacks & Queues are different data structures from LinkedLists
Stack
What is a stack?
A data structure that removes items in reverse of the order in which they
were inserted.
The last item to be inserted will be the next to be removed.
Terminology:
push: adds an item to the collection
pop: removes the most recently added item that has not been
removed yet
A last-in/first-out data structure.
We can implement a stack as a linked list.
Requires very little change from the linked list we have already
implemented.
push: add to the start of the list
pop: remove from the start of the list
Queue
What is a queue?
A data structure that removes items in the same order in which they were
inserted.
The earliest inserted item in the queue will be the next to be removed.
Terminology:
enqueue: adds an item to the collection
dequeue: removes the item that has been in the queue the longest
A first-in/first-out data structure.
We can implement a queue as a linked list.
Requires some change from the linked list we have already implemented.
enqueue: add to the end of the list
dequeue: remove from the start of the list
CSC1016S Lecture 37
Topic: Linked Lists Part 2
Course: CSC1016S
Date: 13/10/2023
Professor/Speaker: Francois Meyer
Summary
Linked Lists
A linked list is the simplest example of a linked data structure.
Single chain of nodes, each connected to the next by a link.
A linked list can be made self-contained by making the node class an inner
class
A node inner class so defined should be made private, unless used
elsewhere.
A linked list can be made self-contained by making the node class an inner
class
A node inner class so defined should be made private, unless used
elsewhere.
This can simplify the definition of the node class by eliminating the need
for accessor and mutator methods
This solves issues related to privacy leaks - makes the private instance
variables of a node inaccessible.
Like other classes, a linked list class should normally have an equals method.
It can be defined different ways, depending on the situation.
Usually checks if two linked lists have the same nodes.
Can check if nodes are in the same order it can be independent of order.
Deep copying vs shallow copying
LinkedList copiedList = list;
This just copies the reference - another name for the same list (a shallow copy).
Would have to traverse a linked list and copy of each node.
Even this would not be a deep copy - for that you have to copy the node
data as well.
Generic Linked Lists
A linked list can be created with a type parameter <T> for the node class type.
This would enable our linked list to store objects of any class type,
including types that contain multiple instance variables.
e.g. linked list of Strings, Integers, Employees, Teams.
This class can have the same methods, coded very similarly (only difference
is node type being a parameter).
Iterators
A collection of objects, such as the nodes of a linked list, must often be
traversed in order to perform some action on each object.
An iterator is any object that enables this.
Can be implemented as an inner class in the linked list class.
Iterator inner class can be made public, so it can be used outside the linked
list class.
LinkedList.ListIterator i = list.iterator();
Linked list class has an iterator method that returns an iterator for that
linked list.
Basic methods for an iterator:
restart: Resets the iterator to the beginning of the list.
hasNext: Determines if there is another data item on the list.
next: Produces the next data item on the list.
addHere: Add a node at the current position in the linked list.
delete: Remove the current node.
changeHere: Modify the current node.
An iterator can be used to add/delete/change nodes at the current position.
This is implemented by reassigning the position and/or previous nodes.
Deleting a node
Code Sample:
previous.link = position.link;
position = position.link;
Adding a node (between previous and position)
Code Sample:
Node temp = new Node(newData, position);
previous.link = temp;
previous = temp;
SIPP Lecture 11
Topic: Intellectual Property
Course: CSC1016S
Date: 12/10/2023
Professor/Speaker: Maria Keet
Summary
Critiques(Selection) on Intellectual Property
Physical possession issue - Information objects, such as numbers and
propositions are abstract objects, which cannot causally interact with material
objects, and hence cannot be owned or possessed
Copies, so no exclusive property - Information is "non-rivalrous", i.e.: intellectual
works are not typically consumed by their use and can be shared concurrently
Rights-based issue - Individuals have a right to knowledge and IP restricts
access, use, and expression of ideas
Protecting Software
Currently three mechanisms:
copyright,
trade secrecy and
patent.
Copyright
Copyright prevents others from copying original works without permission
for a limited time (50 years after death of author)
Only expression of an idea, and not the idea itself, can be copyrighted
Exist in a material form
Copyright comes into being automatically and no registration is required
Software Copyright in South Africa
Computer programs are eligible for Copyright, if they are original
Need permission for:
Reproducing the computer program in any manner or form;
making an adaptation of the computer program; etc
What Constitutes Copyright Infringement?
In general copyright infringement occurs where the copyrighted material of
others is used for personal gain as opposed to private or personal use
Backup is allowed for personal use
Fair dealing is allowed for review, illustration in teaching, demonstration of
equipment
Copyright of programs lasts 50 years after first made available to the public
The author of a computer program is the person who exercises control over the
making of the program
TRADE SECRECY
Trade Secrecy Laws
Grant companies the right to keep information secret
e.g. a secret recipe
allowing them to keep a competitive edge
not designed with computer technology in mind
For a piece of information to be considered trade secret:
It is novel
Represents an economic investment to the claimant
Have involved some effort in development
The claimant made some effort to keep it secret
TRADEMARKS AND DOMAINS
Trademarks
Distinguishes one person's goods or services from those of another
Rights exist either via common law or by registration
Registered Trademarks are perpetually renewable in periods of 10 years
Domain Names
Domain Name System(DNS)
Used instead of IP numbers
generic Top Level Domain(gTLD)
.com, .net, .org etc
PATENTS
Patent Protection I
Gives inventor monopoly on use of the invention
even if someone makes the same product in a different way
Is granted for a limited number of years (20)
The main aim of patents
advance useful arts and science
foster inventions
promotes disclosure of inventions
ideas already in the public domain remain there.
Cannot patent abstract idea, algorithm or scientific principle
Must satisfy the following criteria:
Permissible subject matter
Satisfies the three tests of: utility, novelty and non-obvious.
Patents versus Copyright(practical things)
Software is already protected by copyright law
Copyright rules are simpler
protection available to everyone at very low cost(or nil)
The patent system is cumbersome and expensive
Applying and conducting patent searches can cost a lot
Feasible for large companies like Microsoft
Patenting is South Africa: CIPRO
CIPRO is South Africa's patent office
Companies and Intellectual Properties Registration Office.
In South Africa patents are granted without any examination by the authorities
What is the Lifespan of a Patent?
A patent can last up to 20 years, provided that it is renewed annually before the
expiration of the third year.
It is important to pay an annual renewal fee to keep it in force.
The patent expires after 20 years from the date of application
What can be patented?
1) A patent may, subject to the provisions of this section, be granted for any
new invention which involves an inventive step and which is capable of being
used or applied in trade and industry or agriculture.
2) Anything which consists of:
a) a discovery;
b) a scientific theory;
c) a mathematical method;
d) a scheme, rule or method for performing a mental act, playing a game
etc
Alternatives to Current Intellectual Property Regimes
In response to the misuse of current IP mechanisms to stifle rather than
encourage creativity and innovation a coherent movement has arisen
Open Source or Free Software: Freedom to use, study, modify and share
software
Open Content: Freedom to use, study, modify and share scientific and creative
works
Open Standards: Publicly licensed standards that allow different
hardware/software vendors to make products that interoperate
Copyleft - Richard Stallman
copyleft is a general method for making a program or other work free, and
requiring all modified and extended versions of the program to be free as well
Uses copyright law, but flips it over to serve the opposite of its usual purpose:
instead of privatizing software, it becomes a means of keeping it free
Give everyone permission to:
run the program,
copy the program,
modify the program,
distribute modified versions
but not permission to add restrictions of their own
Thus, the crucial freedoms of "free software" are guaranteed to everyone who
has a copy;
they become inalienable rights
What is FLOSS?
The process with Free/Libre and Open Source Software:
software developer(s) create a piece of software which they think may be
useful
the software, as well as the source code, is made freely available to anyone
the code is then read, modified and improved by other programmers
The original developer(s) usually remain as the custodian(s) of the software,
issuing new releases based on the input from other developers
Essentially it is a means of "peer review", where other developers get to review
code
Licensing: GPL
Each open source project has a license associated with it
This license indicates what rights and responsibilities the user of the software
has
A very common license is the GNU General Public License(GPL) allows the user
to:
freely copy and distribute copies of source code and software, only with
the license
modify code, but those changes must be clear and made available with
same license
CSC1016S Lecture 36
Topic: Linked Lists Part 1
Course: CSC1016S
Date: 10/10/2023
Professor/Speaker: Francois Meyer
Summary
LINKED LISTS PART 1
Linked Data Structures
A linked data structure consists of nodes connected via links.
Nodes store data as instance variables.
In Java nodes are objects of a node class.
Links are one way passages from one node to another (visualised as
arrows).
In Java links are references (memory addresses) stored as instances
variables of the node class type.
Linked Lists
The first node is called the head node
The last node serves as a kind of end marker
Each node is an object of a node class.
Each node contains data and a link to another node.
A piece of data is stored as an instance variable of the node.
Links are implemented as references to a node stored in an instance
variable of the node type.
The node class is crucial to a linked lists. So how do we implement a linked list,
using the node class?
A linked list object does not contain all the nodes in the linked list directly.
Instead, it only contains the head node.
The entire linked list can be traversed by starting at the head.
It has an instance variable of the node type that contains a reference to the
head node.
The head node and every node of the list contain a link instance variable that
provides a reference to the next node in the list.
Linked list implementation details
When head == null, the list is empty.
The last node’s link instance variable is always null. This indicates that we
have reached the end of the linked list.
What do we want to do with a linked list?
Traverse it - from beginning to end.
Add nodes - where? - e.g. at the start.
Remove nodes - which node? - e.g. the first.
How to traverse a linked list
1. Set a variable equal to the head node. Node position = head;
2. Access the next node using the node’s accessor method for the link
instance variable. position = position.getLink();
3. Repeat until position == null.
How to add a node to the start of a linked list?
1. Create a new node and set its link to the current head. Node newHead =
new Node(name, count, head);
2. Set head equal to this new node. head = newHead;
How to remove the first node of a linked list?
1. Set the head node to the second node head = head.getLink();
2. Now the old head node is no longer in the linked list.
3. Java frees up storage used by variables no longer referenced (automatic
garbage collection). Takes care of deleted nodes.
CSC1016S Lecture 35
Topic: Inner Classes
Course: CSC1016S
Date: 09/10/2023
Professor/Speaker: Francois Meyer
Summary
Announcements
No lecture on Wednesday due to test 2
Friday lecture will not be a code demo but a normal class
Inner Classes
Inner classes are classes defined within other classes
the class that includes the inner class is called outer class
inner class can be defined anywhere in an outer class, but convention is at
the start or end of a class definition.
compiling a class with one(or more) inner classes and produces two(or
more) class files
Why use inner classes?
they make outer class more self-contained
outer classes and inner classes have access to each other's private methods
and instance variables
very useful as helping classes(should then be private)
An inner class definition is a member of a class-just like variables and methods
Code Sample:
public class ClassName {
private int num;
public int getNum() {...}
private Class InnerClassName {...}
}
An inner class is local to the outer class definition
If the inner class is private, then the inner class can not be accessed by name
outside the definition of the outer class
Within the definition of the inner and outer class, the modifiers public and
private are equivalent
in the definition of an inner class method, you can access private variables
and methods of the outer class
in the definition of an outer class method, you can access private variables
and methods of the outer class (but you might have to create an object of
the inner class)
Static Inner Classes
But sometimes we want static inner classes:
if an object of the inner class is created within a static method of the outer
class
if the inner class must have static members
the entire body of a non-static inner class is not within a static scope and
therefore you can’t have static members in there
A static inner class has no connection to an outer class object
instance variables of the outer class can not be referenced
non-static methods of the outer class can not be invoked
NOTE: Static inner classes are static for the outer class!
Code Sample:
public class ClassName {
private int b;
private static int b;
private Class NormalInnerClass { ... }
private static Class StaticInnerClass { ... }
}
Public Inner Classes
If an inner class is marked public, then it can be used outside of the outerclass
in the case of a non-static inner class, it must be created using an object of
the outer class
e.g., BankAccount account = new BankAccount();
BankAccount.Money amount = account.new Money("41.99");
the new object amount can now invoke methods from the outer, but only
from within the inner class
A public static inner class can be instantiated - in a static context relative to the
outer class. It will belong to the class, not an instance of the class
OuterClass.InnerClassvinnerObject = new OuterClass.InnerClass();
Note that all of the following are acceptable:
innerObject.nonstaticMethod();
innerObject.staticMethod();
OuterClass.InnerClass.staticMethod();
Nesting Inner Classes
You can define an inner classe with in an inner class:
The rules are the same as before, but then the names get longer. •
Given class A, which has public inner class B, which has public inner class C,
then the following is valid:
A aObject = new A();
A.B bObject = aObject.newB();
A.B.C cObject = bObject.newC();
Inner Classes and Inheritance
An outer class can be a derived class
An inner class can be a derived class
Given an OuterClass that has an InnerClass:
any Derived Class of OuterClass will automatically have InnerClass as an
innerclass
in this case, the DerivedClass can not override the InnerClass
Anonymous Class
An anonymous class is a class without a name
definition is embedded inside the expression with the new operator
useful when you only use a class once
sometimes anonymous classes are assigned other types(e.g. interfaces such
as Comparable)
all anonymous classes are examples of inner classes
CSC1016S Lecture 34
Topic: Code demo
Course: CSC1016S
Date: 06/10/2023
Professor/Speaker:Francois Meyer
Summary
The Sort method
From java.util.Collections.*;
The sort method arranges a series of values in order
code sample:
import java.util.Collections.*;
public class SortSample {
int[]array = {3,1,2};
int[]sortedArray = Collections.sort(array);}//will sort the array in
ac=scending order, i.e., {1,2,3}
Selection Sort
Easiest method to sorting an array of things
The process: takes first element in list, compares with the rest of the
elements to find an element that comes before it, then if it does, the two
switch positions, and the process continues for all the individual elements
until the array is sorted
In java, abstract classes do not have constructors and thus they don't have
objects
GenericsDemo
If not sure of which type parameter to use, just use T, and the type parameter
will be specified at runtime
SIPP Lecture 10
Topic: Privacy & Intellectual Property
Course:CSC1016S
Date: 05/10/2023
Professor/Speaker: Maria Keet
Summary
South Africa: the POPIA
A few tidbits for illustration:
includes the 'right to be forgotten'
A responsible party must take reasonably practicable steps to notify a data
subject when collecting personal information
Right to request, free of charge, whether or not the responsible party holds
personal information about them, as well as a description of the personal
information held
ACM Code of Conduct
Minimize data collection
Only allow authorised access to data
Provide proper security
Determine required retention period
Ensure proper disposal of data
Privacy and Ubuntu
Ubuntu is a community-based mindset
Ubuntu has no concept of privacy
core of privacy is to protect dignity: in harmony with ubuntu
Protect Your Online Privacy
Electronic Frontier Foundation(EFF) is an organisation that protects rights and
promotes freedom in the electronic frontier, including an individuals right to
privacy
INTELLECTUAL PROPERTY
Can, or do, you own software?
No, the company of that software is the one that owns it, you can only get
license
Objective of Intellectual Property
Promote progress
except trademark
Fair exchange of for mutual benefit:
creator gets limited exclusive rights
society gets disclosure of inventions and creative works
Incentive is created for inventors and and authors to create and disclose their
work
Intellectual Property
Designs
does not cover how the article functions(unlike patent)
protects physical appearance of a manufactured object
Copyright
computer programs and data
computer program's "author" is the person who exercises control over the
making of a computer program
Trade secrets-not really property
law protects industrial secrets
Trademarks-forever
Patents-20 years in South Africa
innovations
do not apply to software (yet)
Philosophical Basis of Intellectual Property
1) Labour Theory(John Locke): A property right is a "natural right" and property
rights can be justified by the labour or "toil" that one invents in cultivating land
or in creating a work of art
2) Utilitarian Theory(Incentives-Based): Property rights are "artificial rights"
created by the state. Property rights are granted to individuals and to
corporations because they result in greater social utility overall
3) Personality Theory(Hegel): A property right is a "moral right" and property
rights are justified because creative works express the personalities (talents,
feelings, ...) of the authors that create them
CSC1016S Lecture 33
Topic: Generics
Course: CSC1016S
Date: 04/10/2023
Professor/Speaker: Francois Meyer
Summary
Announcements
Generics is the last topic to be covered for the upcoming test 2
There's a lecture this upcoming Friday
Generics
Created in the same way as object of any class except that you specify the base
type
Base type must be a reference type
The class ArrayList is an example of a parameterized class or generic class
Public class Sample<T>//T is the type parameter
A type parameter can have any reference type(e.g any class type) plugged in for
the type parameter
Traditionally. a simple uppercase letter is used for a type parameter, not any
non-keyword identifier may be used
Generic constructor definition has no type parameter
e.g., public class Pair<T>{
public Pair(T varA, T varB){
Pair<String> p = new Pair<String>("Abc")}}
The following are not allowed in Java:
T object = new T()//illegal
T[] a = new T[10]//illegal
pair<string> a = new pair<string>[10]//illegal
A generic class definition can have any number of type parameters, e.g., public
class ClassName<T1,T2>{...}
Inheritance and interfaces can be set with generic classes
public class ClassName<T> extends BaseClass
public class ClassName<T> implements Comparable
public class ClassName<T> extends BaseClass<T>
Generic class can extend normal class but normal class cannot extend generic
Sometimes you want to restrict the possible type that can be plugged in for a
type parameter T, This is done by placing 'bounds'' on types (compiler will
check)
public class ClassName <T extends comparable>
only classes implementing Comparable interface can be plugged in for
T
public class ClassName<T extends BaseClass>
only descendent classes of BaseClass can be plugged in for T
public class ClassName<T extends BaseClass & Comparable & Ordered>
a bound expression may contain multiple interfaces and up to one
class
Interfaces can have parameterised types(details and notation are the same as
for generic classes)
public interface Ordered<T>
public class Example implements Ordered<String>//specify type T, in this
case T= String
Methods can be generic, having their own type parameters
method heading: public<T> T gen(T[]a)[....]
method invocation: String s = new Object.gen<T>(T[]a);
CSC1016S Lecture 32
Topic: Interface & ArrayList
Course: CSC1016S
Date: 03/10/2023
Professor/Speaker: Francois Meyer
Summary
Announcements
Test 2 next week Wednesday
Test will cover everything from(and including) UML Diagrams to
Generics(included)
Interface & ArrayList
Marker Interface
is an empty (no method headings or constants) interface class
used to tag a class as having a specific property/behaviour, but it won't
necessarily be enforced
instanceOf() can check if an object type implements a marker interface
Cloneable
Extreme but commonly used interface
Completely empty - no method headings or constants
Used to indicate that the clone() can be used safely
Serializable
Extreme but commonly used interface
Completely empty - no method headings or constants
Type tag indicating that it implements file I/O in a particular way
Comparable
Not a marker interface
Many things can be ordered/ranked/sorted
Comparable lets us apply one sorting algorithm to all these classes
Provides sorting functionality to any class
Has only method heading that must implemented
code sample:
public int compareTo(Object other)
//Parameters: the object to be compared
//Returns:- negative number if this object preceded other
- zero if equal
- positive number if this object follows other
The ArrayList Class
Class in the standard Java libraries (requires import java.util.ArrayList)
Similar to arrays, except ArrayList length can change while the program is
running
Implemented using array instance variable
ArrayList has the same purpose as arrays, but array size is fixed - ArrayList size
can change dynamically
The downsides
not convenient for square bracket notation
base type of an ArrayList must be a class type (or other reference type); it
can not be a primitive types
can't create an ArrayList of ints - only of Integers, but Java provides
automatic boxing
code sample:
ArrayList<Base_Type> l = new ArrayList<Base_Type>();//creates a new
arraylist object to store items
Created in the same way as object of any class, except that you specify the base
type
Base type must be a reference type (e.g. class, interface)
An initial capacity can be specified when creating an ArrayList
e.g, ArrayList<Base_Type> l = new ArrayList<Base_Type>(20);//this is more
efficient but size can still change dynamically
ArrayList Method Examples
1) add() - adds new item to arraylist
2) set(int index, Type item) - sets item at given index
3) remove(Object item) - checks and removes first occurrence of item
4) indexOf(Object item) - returns first index of item
5) size() - returns size of arraylist
6) get(int index) - returns items at given index
7) contains(Object item) - returns true if list contains item and false if not
8) isEmpty() - returns true if list is empty and false if not
9) toArray() - returns array that contains all elements in arraylist
10) clone() - creates shallow copy of arraylist (both copy and original arraylists
have same reference position)
for-each loop
for(String element : list)
{
System.out.println(element); //will print every element in list
}
CSC1016S Lecture 31
Topic: Interface
Course: CSC1016S
Date: 02/10/2023
Professor/Speaker: Francois Meyer
Summary
INTERFACE
An interface simply specifies which methods a class has to have(no method
definitions, only headers)
An interface class contains:
methods heading
constant definitions
no method definitions
no instance variables
An interface is like an extreme form of abstract classes
Code sample:
public interface Ordered
{
public boolean precedes(Object other);
public boolean follows(Object other);
}
Use keyword implements next to class definition to implement an interface
class
An interface and its methods must be declared public (always)
When a class implements an interface it must make all methods in the interface
public (cannot lower access scope)
An interface is a type
Java does not allow multiple inheritance, but we can approximate it by
implementing multiple interfaces
A class can implement multiple interfaces
e.g., public class implements Class1,Class2
Abstract classes can also implement interfaces
Interface methods not given definitions are made abstract methods
Like classes, an interface may be derived from a base interface
What is the purpose of interfaces?
shared functionality, but no shared implementations
an interface is a blueprint for a class
it is a 'contract' between the class and outside world
approximates multiple inheritance for Java
Problems with interface: interface syntax is enforced, semantics is not
java does not check whether methods do what they should
that is the responsibility of the programmer - read the docs
Differences between interface and abstract classes
interface classes have no methods implemented while abstract classes have
some methods implemented
interface classes define functionality but does not implement any, while
abstract classes define some functionality, implements others
interface methods can only be public while methods can be anything
except private
Similarities between interface and abstract classes
both are types
can be used as method parameter types
can be used as variable types
neither one can be used to create objects
interfaces cannot have constructors nor instance variables
Are the following allowed in Java
public void sort(Ordered orderList) - YES, an interface is a type and allows
any class that implements it to use the type as a parameter type
Ordered orderList = new Ordered() - NO, interfaces do not have
constructors, nor instance variables
Ordered orderList = new Employee- YES, as long as Employee implements
Ordered
Interfaces can contain method headings and defined constants
A class that implements the interface has access to the constants
All the constants must be:
public - so implementing classes have access to them
static - because interfaces cannot be instantiated in their own right, the
value of the variable must be assigned in a static contect in which no
instance exists
final - ensure they are true
Java does not allow multiple inheritance, preventing inconsistencies arising
from the same method heading having different definitions
a class can implement multiple interfaces, but allows inconsistencies
Possible conflicts with multiple interfaces:
interface classes may have constants with same name, but different values
interface classes may have methods with same name but different return
types
Methods with same names, same return types: will run but unclear
Methods with same names, different parameter types will run
clearer(overloading)
CSC1016S Lecture 30
Topic: Workshop
Course: CSC1016S
Date: 29/09/2023
Professor/Speaker:
Summary
HOW TO PREPARE FOR EXAMS
by Jean
There's no such thing as being smart/dumb - only those who have a fixed
mindset and those who have a growth mindset
CS takes a drastic change after 1016
Setting yourself up for success
Know when is your best time to study (i.e., morning, noon or night)
Use Excel spreadsheet (or any other program) to track your progress
Exercise
Get sufficient sleep
Be always consistent
Take breaks - try the promodoro technique or something similar
Understand that most people don't have more than 4 hours of deep learning a
day
The core of this presentation
These won't work:
Passive re-reading of slides
Aimlessly doing past papers
Working for hours on end no breaks
Start now, mastering little bits at a time
Even 20 mins a day is better than nothing
Don't fall into the trap of if i cant do it all i shouldn't do it at all
The brain, i.e. your focus can be trained, like anything else
Anything worth archiving takes effort, please make peace with this
https://github.com/janeimrie
by Claudius
Coding is like maths, it requires practice
Trying coding on paper to test your understanding of the topics
Go over examples in the slides - practice makes perfect
Try to understand every single line of code in a program
Master the concepts first and then use programming as a tool
It is better to work with friends and seek help instead of doing things alone
by Ciara
Useful course resources:
whatsapp group
vula site for past exams
hotseat
lab sessions
go to the disability unit if you have need for accommodation
Documentations
ubuntu
Don't plagiarize any code, instead understand what every line means
Practising coding is about learning how to break down problems into smaller
manageable pieces, and then solving it
examples of useful websites: codechef, geegforgeeg,imaginecup etc
Honours in computer sciences requires a minimum of 65 in all courses
SIPP Lecture 09
Topic: Privacy and Civil Liberties
Course: CSC1016S
Date: 28/09/2023
Professor/Speaker: Maria Keet
Summary
PRIVACY AND CIVIL LIBERTIES
Define Privacy
It is about drawing a boundary in order to withdraw from others or withdraw
information
Tied up with what we value about it:
we value some control over who knows what about us
and worries about how we can loose it via surveillance:
advances in IT have reduced our control over personal data
Cookies:
enables site owners to collect data about those who use their sites
stored on the users computer
Privacy is sometimes viewed in terms of something that can be diminished or
lost altogether
Privacy is also sometimes construed in terms of the metaphor of a (spatial)
zone that can be intruded upon or invaded
Privacy is also sometimes analysed in terms of concerns affecting the
confidentiality of information, which can be breached or violated
Three Views of Privacy
Accessibility privacy -Privacy is defined as one's physically being let alone, or
being free from intrusion into one's physical space
Decisional privacy-Privacy is defined as freedom from interference in one;s
choices and decisions
Informational privacy-Privacy is defined as control over the flow of one's
personal information, including the transfer and exchange of that information
Kant's Theory
Privacy is essential to autonomy
Autonomy is inconceivable without privacy
Preserving privacy fosters
individual autonomy,
dignity,
self-determination.
Privacy ultimately promotes a more robust, participatory citizenry
Privacy is important for democracy
Unwanted exposure may lead to
discrimination,
loss of benefits,
loss of intimacy,
stigma, and
embarrassment
South African Bill of Rights
Everyone has the right to privacy, which includes the right not to have
their person or home searched;
their property searched;
their possessions seized; or
the privacy of their communication infringed.
Protection of Personal Information Act(POPIA or POPI)
Sets conditions for how you can process information
It has been signed by the President and is law
General Information Protection Principles
Those who process personal Information
generally, anyone with customers, partners or staff who store their
personal information in some way
Collect only information needed for a specific purpose
Apply reasonable security measures to protect information
Only hold as much information as needed for as long as needed
Allow the subject of the information to view it upon request
If information is transferred across borders must ensure compliance with
the restrictions in terms of the PoPI Act
If information is used for direct marketing the data subject has to give his
or her consent or be a customer
CSC1016S Lecture 29
Topic: CHAPTER 8 - Polymorphism & Abstract classes
Course: CSC1016S
Date: 27/09/2023
Professor/Speaker: Francois Meyer
Summary
Announcements
Slides available under relevant chapters in OOP Java
Lecture slides are uploaded after every lecture
There's a lecture this Friday
ABSTRACT CLASSES
An abstract class is defined to present a general category
Partially implemented (some methods, some attributes)
explicitly leaves some methods unimplemented
then, specialised versions of the class are defined - concrete classes
the child class inherits methods and variables from the abstract class these
attributes are required to be defined
Classes derived from abstract classes can also:
add additional instance variables and methods
override methods from the base class
be abstract
An abstract method is like a placeholder for a method that will be fully defined
in descendent class
it has a heading, but no method body
the body is defined in the derived concrete class
code sample:
public abstract class Shape{
public abstract double perimeter();
public abstract double area();}
Abstract class can have defined methods and instance variables
they will then be inherited along with the abstract attributes
What is the idea?
To postpone the definition of a method to the derived concrete class
Cannot create create an object of an abstract class
Abstract methods cannot be made private because they have to be
overridden(defined) in a concrete descendent class; private methods cannot be
accessed/overridden
Abstract methods cannot be made static because static methods cannot be
overridden;static binding- methods definitions bound during compile time
A class derived from an abstract class can be made abstract as well
e.g., public abstract class Circular extends Shape{...}
Then this class would have to be further derived to finally create a concrete
class
e.g., public class Circle extends Circular{...}
An abstract constructor cannot be used to create an object of the abstract class
But it can still be used to call super()
Abstract classes are types
parameter types can be abstract class type
variable types can be abstract class type
e.g., Shape c = new Circle();
Variable type vs object type
Compile-time time, i.e., What methods are accessible
Runtime type i.e. what methods implementations are executed
CSC1016S Lecture 28
Topic: CHAPTER 8 - Polymorphism and abstract classes
Course: CSC1016S
Date: 26/09/2023
Professor/Speaker: Francois Meyer
Summary
Object is the ancestor of all classes
Every object is the type of its own class, as well as of the type Object
The Clone Method
A First Look at the clone Method
Every object inherits a method named clone from the class Object
The method clone has no parameters
It is supposed to return a deep copy of the calling object
However, the inherited version of the method was not designed to be used as
is
Instead, each class is expected to override it with a more appropriate
version
The heading for the clone method defined in the Object class is as follows:
protected Object clone()
The heading for a clone method that overrides the clone method in the Object
class can differ somewhat from the heading above
A change to a more permissive access, such as from protected to public, is
always allowed when overriding a method definition
Changing the return type from Object to the type of the class being cloned
is allowed because every class is a descendent class of the class Object
This is an example of a covariant return type
If a class has a copy constructor, the clone method for that class can use the
copy constructor to create the copy returned by the clone method
The copy constructor and clone method seem to do the same thing, but clone
is polymorphic and the copy constructor is NOT.
For example, given a method badcopy in the class Parent that copies an array
of parent objects
If this array of parents contains Child objects, then the copy constructor will
return Parent objects.
b[i] = new Parent(a[i]); //unsafe!
b[i] = a[i].clone(); //safe, assuming clone() is correct
code sample:
public Employee clone()
{
return new Employee(this);}
Pitfall: Limitations of Copy Constructors
If the clone method is used instead of the copy constructor, then (because of
late binding) a true copy is made, even from objects of a derived class.
b[i] = a[i].clone();
The reason this works is because the method clone has the same name in
all classes, and polymorphism works with method names
The copy constructors named Sale and DiscountSale have different names,
and polymorphism doesn't work with methods of different names.
Java does not have Polymorphic constructors (unlike e.g. Pascal)
CSC1016S Lecture 27
Topic: Chapter 8 - Polymorphism
Course: CSC1016S
Date: 22/09/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
This is Aslam's last lecture
ASSIGNMENT 09
Question 01
Identify inheritance relationship and polymorphism, which will be used for the
question
Need to create a base class, and then create an array or arraylist of the base
class type
You can give the base class any name
Check what automarker expects, then implement it
Question 02
VectorObject is the base class for HLine, VLine, PtLine and Rectangle
The class VectorGraphics will do all the drawing
Question 03
Will require more of inheritance and relationships than polymorphism
SALE & DISCOUNTSALE PROGRAMME
Programmes can be found in Resources>>Code Samples-Safla>>Chapter 8
When a parent object is assigned a child type instance, it's called upcasting
Definition of method is taken from the class where it was defined originally
Only if we have an overridden parent method, can we have polymorphism take
place(i.e., we can not access child method that was not overriden from the
parent class)
When parent instance is assigned child class type, it's called downcasting (child
class type must be in brackets)
To use child method that was not overridden in parent class, first downcast
parent class instance
SIPP Lecture 8
Topic: Introduction to Values & Analysing tools
Course: CSC1016S
Date: 21/09/2023
Professor/Speaker: Maria Keet
Summary
The structure of an argument: standard(basic) form
Premise 1
…
optional
…
optional
Premise N
optional
Conclusion
The form of a valid deductive argument
A valid argument is valid solely in virtue of its logical form, regardless its
content
An example of a valid logical form is:
Premise 1. Every A is a B.
Premise 2. C is an A.
Conclusion: C is a B.
No matter which values are substituted for A, B, and C, the argument in this
form is always valid.
modus ponens (implication elimination)
Premise 1. A implies B
Premise 2. A is true
Conclusion: B is true
Counterexamples to arguments
A counterexample is:
A possible (actual) case where the premises in an argument can be
imagined to be (is) true while, at the same time, the conclusion could still
be false
Note that if a deductive argument is valid, no counterexample is possible
To put it differently: if you can give one counterexample to the argument
then it is invalid.
In informal reasoning, appeal to “the exception to the rule” is sometimes made
It makes your informal argument a lot weaker to argue for
Double-check if it is really a counterexample (maybe your opponent tries to
sidetrack you)
Types of Inductive Arguments
Inductive generalisations:
The premise identifies a characteristic of a sample of a population
The conclusion extrapolates that characteristic to the rest of the
population.
‘Causal’ generalisations:
The premise identifies a correlation between two types of event
The conclusion states that events of the first type cause events of the
second type.
But beware of causation vs correlation…http://www.tylervigen.com/spuriouscorrelations
Arguments from analogy:
Arguments from analogy take one example of something
Then extrapolate from a character of that example…
…. to the character of something similar to that thing
Arguments from authority:
Take one person or group of persons
Who are, or are assumed to be, right about some things…
And extrapolate to the claim they are right about other things
But beware of the ‘appeal to authority’ fallacy
Evaluating Inductive Arguments:
Inductive Generalizations
Is the premise true?
How large is the sample?
How representative is the sample?
e.g.: 50 students answering a question in class vs 500 who nswered the pop
quiz on Vula
Beware ‘informal’ heuristics (rules of thumb)
Evaluating Inductive Arguments: Arguments from analogy
are the two things similar?
e.g.: an email and a postcard; Social media as a comms medium
are they similar in respect of something relevant?
can we find a disanalogy?
where the analogy fails in exactly the feature we need to compare
Premise 1: 75% of Apple Mac owners also own iPhones.
Premise 2: My new bae owns an Apple Mac.
Conclusion: My bae owns an iPhone.
Analysing Arguments: identify it by converting to standard form
1. identify the conclusion of the argument;
2. identify each of the premises;
3. add suppressed (assumed) premises
4. remove irrelevancies;
5. remove inconsistent terms;
6. remove cross-references.
At this stage do not evaluate the argument
Analysing Arguments: check the reasoning
Test the argument for its reasoning strength
For a deductive argument:
see whether it is valid or invalid.
assume the premises to be true, and ask yourself whether the
conclusion must also be true when those premises are assumed true.
Now see if the argument is sound, that is, are the premises true in the
actual world?
For an inductive argument, see if it is weak or strong
see earlier: inductive generalisations and causal generalisations; arguments
from analogy and authority
Is a counterexample to the argument possible?
Analysing Arguments: make an overall assessment
Describe the argument's strength of reasoning in conjunction with the truth
conditions of the argument's premises.
For example is the argument:
deductive and sound?
inductive with all true premises?
inductive with some false premises?
fallacious with a mixture of true and false premises?
…?
Remember that an inductive argument with premises that are all true is useful
while a valid argument with one or more false premises says nothing
Example: what are the arguments?
A computer equipped with signature-recognition software, which restricts
access to a computer to those people whose signatures are on file, identifies a
person’s signature by analysing not only the form of the signature but also such
characteristics as pen pressure and signing speed. Even the most adept forgers
cannot duplicate all of the characteristics the program analyses.
1. Access to the computer is restricted by means of signature-recognition
software.
2. Such software cannot be fooled by even the best forger.
FALLACIES
It means faulty reasoning
We have already seen that it is possible for an argument to contain all true
statements and still be (logically) fallacious
There are very many kinds of (informal) fallacies
http://www.fallacyfiles.org
In particular we are going to look at fallacies of:
relevance
vacuity
clarity
Fallacies of relevance
Citing in support of a conclusion something that is true but irrelevant (nonsequitur):
Bill lives in a large building, therefore his apartment is large.
Every year many people are supported through life by their religious
beliefs, so their religious beliefs must be true
Attacking the person making the argument rather than the argument that is
made (ad hominem)
How can we take seriously a position regarding the future of our national
defense that has been opposed by MP X, who has been arrested for
drunken driving and who has been involved in extramarital affairs?
Note that an ad hominem attack is not the same as an ad hominem fallacy
Fallacies of vacuity
Citing in support of a conclusion that very conclusion (circular arguments)
In a circular argument the conclusion is one of the premises
Citing in support of a conclusion a premise that assumes the conclusion
(begging the question)
In a question-begging argument the conclusion is assumed by one of the
premises
Straw man I
The straw man fallacy is when you misrepresent someone else's position so that
it can be attacked more easily, then knock down that misrepresentedposition,
then conclude that the original position has been demolished.
It's a fallacy because it fails to deal with the actual arguments that have been
made.
CSC1016S Lecture 25
Topic: CHAPTER 7- INHERITANCE
Course: CSC1016S
Date: 19/09/2023
Professor/Speaker: Aslam Safla
Summary
Encapsulation and Inheritance Pitfall: Use of Private Instance Variables
from the Base Class
An instance variable that is private in a base class is not accessible by name in
the definition of a method in any other class, not even in a method definition of
a derived class
This is to prevent privacy leaks
Instead, a private instance variable of the base class can only be accessed by
the public accessor and mutator methods defined in that class
A private method in the parent class is invisible to the child class and thus it is
not inherited when the child extends the parent class
A method with the same signature as the parent's private method can be
created in the child class
Protected and Package Access
Private is least accessible(i.e., can not be accessed anywhere outside the class
it's defined in) and public is most accessible(i.e., can be accessed by any class )
If a method or instance variable is modified by protected (rather than public or
private), then it can be accessed by name
Inside its own class definition
Inside any class derived from it
In the definition of any class in the same package
The protected modifier provides very weak protection compared to the private
modifier
It allows direct access to any programmer who defines a suitable derived
class
Therefore, instance variables should normally not be marked protected
An instance variable or method definition that is not preceded with a modifier
has package access(default visibility)
Package access is also known as default or friendly access
Instance variables or methods having package access can be accessed by name
inside the definition of any class in the same package
However, neither can be accessed outside the package
If a derived class that's not in the same package as the parent can not
access package
Note that package access is more restricted than protected
Package access gives more control to the programmer defining the classes
Whoever controls the package directory (or folder) controls the package
access
Visibility hierarchy(from most to least access)
public >> protected >> package >> protected
Tip: "Is a" Versus "Has a"
A derived class demonstrates an "is a" relationship between it and its base class
Forming an "is a" relationship is one way to make a more complex class out
of a simpler class
For example, an HourlyEmployee "is an" Employee
HourlyEmployee is a more complex class compared to the more general
Employee class
Another way to make a more complex class out of a simpler class is through a
"has a" relationship
This type of relationship, called composition, occurs when a class contains
an instance variable of a class type
The Employee class contains an instance variable, hireDate, of the class
Date, so therefore, an Employee "has a" Date
HINT:
Is a >> Inheritance relationship
Has a >> Composition relationship
Tip: Static Variables Are Inherited
Static variables in a base class are inherited by any of its derived classes
The modifiers public, private, and protected, and package access have the same
meaning for static variables as they do for instance variables
Access to a Redefined Base Method
Within the definition of a method of a derived class, the base class version of an
overridden method of the base class can still be invoked
Simply preface the method name with super and a dot
You Cannot Use Multiple supers
It is only valid to use super to invoke a method from a direct parent
Repeating super will not invoke a method from some other ancestor class
The Class Object
In Java, every class is a descendent of the class Object
Every class has Object as its ancestor
Every object of every class is of type Object, as well as being of the type of
its own class
If a class is defined that is not explicitly a derived class of another class, it is still
automatically a derived class of the class Object
The class Object is in the package java.lang which is always imported
automatically
Having an Object class enables methods to be written with a parameter of type
Object
The class Object has some methods that every Java class inherits
For example, the equals and toString methods
Tip: getClass Versus instanceof
Many authors suggest using the instanceof operator in the definition of equals
Instead of the getClass() method
The instanceof operator will return true if the object being tested is a member
of the class for which it is being tested
However, it will return true if it is a descendent of that class as well
It is possible (and especially disturbing), for the equals method to behave
inconsistently given this scenario
POLYMORPHISM
Polymorphism is the ability to associate many meanings to one method name
It does this through a special mechanism known as late binding or dynamic
binding
CSC1016S Lecture 23
Topic: ASSIGNMENT 8
Course: CSC10162
Date: 15/09/2023
Professor/Speaker: Aslam Safla
Summary
ANNOUNCEMENTS
Theory test 1 marks have been uploaded, along with the feedback
We'll be having a mark query session next week
If test was marked by Aslam, don't go for query
ASSIGNMENT 8
Is about arrays and basic inheritance
Each class should have a constructor
Each class should have a toString() method
Question 1
The NumberUtils class contains a collection of routines for working with
integers.
It breaks up a number into individual digits and makes an array with them
Assume number A and B have the same length and have no repetitions
Question 2
This question concerns the construction of a simple game called ‘Cows and
Bulls’ that is implemented using the NumberUtils class of question one.
The game involves guessing a mystery 4 digit number. The number contains no
repeat digits and no zero.
With each guess, the number of correct digits – bulls – and the number of
digits that would be correct if they were in the right position – cows.
For example, say the mystery number is 8657 and the player guesses 4678,
there is one bull (6), and two cows (7, 8).
Class randomly generates a secret number using a seed
Result() gives the number of cows and bulls
Question 3
Write a program to demonstrate the use of inheritance by creating and
outputting 3 simple objects, where the classes for the second and third objects
inherit from the class for the first object.
The first object is a Shape with a name and colour. The second object is a
Rectangle with additional length and width. The third object is a Circle with
additional radius.
Use the provided Question3.java file. Use constructors and override methods as
appropriate.
Code Sample:
Java DocString is a string of comments contained in /** .... **/
public class Employee{
private String name;
private Date hireDate;
public Employee(){
name = "no name";
hireDate =new Date("Jan",1,2004)}
public Employee(String name, Date d){
this.name = name;
hireDate = d}
public String getName(){return name//String is immutable so no need for
copy constructor}
public String getDate(){ return new Date(hireDate)//Date is mutable so we
return a copy of the original date}}
public class HourlyEmployee extends Employee{
private double wageRate;
private double hours;//for the month
public HourlyEmployee(){
super();//for a base class to access something from the super class, use
keyword super(), especially if it's something ambiguous. Super calls noargument constructor of the super class
wageRate = 0;}
public HourlyEmployee(HourlyEmpoyee originalObject){
super(originalObject);//It will extract name and hireDate from
HourlyEmployee to Employee(automatically)}
Child class uses parent methods as if they are its own, i.e. no need to create
parent object
SIPP Lecture 7
Topic: ESSAY WRITTING WORKSHOP
Course: CSC1016S
Date: 14/09/2023
Professor/Speaker:
Summary
ESSAY WRITTING WORKSHOP
What is academic writing?
Academic writing is a formal style of writing used in universities and
scholarly publications.
BASIC CHARACTERISTICS
Clear structure
Appropriate Academic Register
Language and Grammar
THE ACADEMIC WRITING PROCESS
1) INTRODUCTION
Contains:
Context
Thesis
Roadmap
2) BODY PARAGRAPHS
Adds information
Explains/Elaborates the general topic
CONSTRUCTING A STRONG ARGUMENT
Coherence - Overall flow from paragraph to paragraph
Cohesion - Overall flow from statement to statement
3) CONCLUSION
Synthesis on main reasoning from essay
So what?
What is your total reason
4) REFERENCING
To be used when summarizing point from a source or when quoting from a
source
Each sentence taken from source should include a reference
How To Determine When To Cite?
When not to cite:
If the idea is originally from your own thinking
If the idea is common sense or knowledge
When to cite:
If idea has been inspired by a source your read
If it's someone else's words
Use quotations sparingly
If the idea is from your ownthinking
CSC1016S Lecture 22
Topic: CHAPTER 7 - Inheritance
Course: CSC1016S
Date: 13/09/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
New version of assignment 7 has been uploaded
No extension for assignment 7
There's a lecture this week Friday and next week Friday
INHERITANCE
Follows class hierarchy
Deals with parent-child relationship
Child inherits all properties of parent, and possibly more properties not from
parent
Introduction to Inheritance
Using this technique, a very general form of a class is first defined and
compiled, and then more specialized versions of the class are defined by
adding instance variables and methods
The specialized classes are said to inherit the methods and instance
variables of the general class
Inheritance is the process by which a new class is created from another class
the new class is called a derived class (or child class or subclass)
the original class is called the base class(or parent class or super class)
A derived class automatically has all the instance variables and methods of the
base class, and it can have additional methods and/or instance variables as well
Inheritance allows code reuse without having to copy the code
again(redundancy)
Derived Classes
Example, Employee class(parent class) has HourlyEmployee and
SalaryEmployee(child classes)
code sample:
public class HourlyEmployee extends Employee//HourlyEmployee will
inherit all the properties of Employee
The class HourlyEmployee inherits the methods getName, getHireDate,
setName and setHireDate from the class Employee
A derived class is defined by starting with another already defined class(base
class), and adding(and/or changing) methods, instance variables, and static
variables
In Java child class can only extend one parent class, and a child class can be
used a parent for another class
CSC016S Lecture 21
Topic: Chapter 6 - Arrays
Course: CSC1016S
Date: 12/09/2023
Professor/Speaker: Aslam Safla
Summary
CHAPTER 6 - ARRAYS
Introduction to Arrays
An array is a data structure used to process a collection of data that is all of the
same type
An array behaves like a numbered list of variables with a uniform naming
mechanism
Creating and Accessing Arrays
The individual variables that together make up the array are called indexed
variables
They can also be called subscripted variables or elements of the array
The number(or variable) in square brackets is called an index or subscript
In Java, indices must be numbered starting with 0, and nothing else
The number of indexed variables in an array is called the length or size of the
array
When an array is created, the length of the array is given in square brackets
after the array type
The indexed variables are then numbered starting with 0, and ending with the
integer that is one less than the length of the array
An array can have indexed variables of any type, including any class type
All of the indexed variables in a single array must be of the same type, called
the base type of the array
The for loop is ideally suited for performing array manipulations
Three Ways to Use Square Brackets [] with an Array Name
Square brackets can be used to create a type name:
double[] score;
Square brackets can be used with an integer value as part of the special syntax
Java uses to create a new array:
score = new double[5];
Square brackets can be used to name an indexed variable of an array:
max = score[0];
An array is considered to be an object
Since other objects can have instance variables, so can arrays
Every array has exactly one instance variable named length
When an array is created, the instance variable length is automatically set
equal to its size
The value of length cannot be changed (other than by creating an entirely
new array with new)
Pitfall: Array Index Out of Bounds
When an index expression evaluates to some value other than those allowed by
the array declaration, the index is said to be out of bounds
An out of bounds index will cause a program to terminate with a run-time
error message
Array indices get out of bounds most commonly at the first or last iteration
of a loop that processes the array: Be sure to test for this!
Initializing Arrays
An array can be initialized when it is declared
Values for the indexed variables are enclosed in braces, and separated by
commas
int[] age = {2, 12, 1};
The array size is automatically set to the number of values in the braces
Given age above, age.length has a value of 3
Another way of initializing an array is by using a for loop
double[] reading = new double[100];
int index;
for (index = 0;
index < reading.length; index++)
reading[index] = 42.0;
If the elements of an array are not initialized explicitly, they will automatically
be initialized to the default value for their base type
Pitfall: An Array of Characters Is Not a String
An array of characters is conceptually a list of characters, and so is conceptually
like a string
However, an array of characters is not an object of the class String
char[] a = {'A', 'B', 'C'};
String s = a; //Illegal!
An array of characters can be converted to an object of type String, however
The class String has a constructor that has a single parameter of type char[]
String s = new String(a);
The object s will have the same sequence of characters as the entire array a
("ABC"), but is an independent copy
Another String constructor uses a subrange of a character array instead
String s2 = new String(a,0,2);
Given a as before, the new string object is "AB"
An array of characters does have some things in common with String objects
For example, an array of characters can be output using println
System.out.println(a);
Given a as before, this would produce the output ABC
Arrays and References
Like class types, a variable of an array type holds a reference
Arrays are objects
A variable of an array type holds the address of where the array object is
stored in memory
Array types are (usually) considered to be class types
Arrays Are Objects
The previous steps can be combined into one statement
double[] a = new double[10];
Note that the new expression that creates an array invokes a constructor that
uses a nonstandard syntax
Not also that as a result of the assignment statement above, a contains a single
value: a memory address or reference
Since an array is a reference type, the behavior of arrays with respect to
assignment (=), equality testing (==), and parameter passing are the same as
that described for classes
Array Parameters
Both array indexed variables and entire arrays can be used as arguments to
methods
An indexed variable can be an argument to a method in exactly the same
way that any variable of the array base type can be an argument
double n = 0.0;
double[] a = new double[10];//all elements
//are initialized to 0.0
int i = 3;
Given myMethod which takes one argument of type double, then all of the
following are legal:
myMethod(n);//n evaluates to 0.0
myMethod(a[3]);//a[3] evaluates to 0.0
myMethod(a[i]);//i evaluates to 3,
//a[3] evaluates to 0.0
Array arguments behave like objects of a class
Therefore, a method can change the values stored in the indexed variables
of an array argument
A method with an array parameter must specify the base type of the array only
BaseType[]
It does not specify the length of the array
Pitfall: Use of = and == with Arrays
Because an array variable contains the memory address of the array it names,
the assignment operator (=) only copies this memory address
It does not copy the values of each indexed variable
Using the assignment operator will make two array variables be different
names for the same array b = a;
The memory address in a is now the same as the memory address in b:
They reference the same array
A for loop is usually used to make two different arrays have the same values in
each indexed position:
int i;
for (i = 0;
(i < a.length) && (i < b.length); i++)
b[i] = a[i];
Note that the above code will not make b an exact copy of a, unless a and
b have the same length
For the same reason, the equality operator (==) only tests two arrays to see if
they are stored in the same location in the computer's memory
It does not test two arrays to see if they contain the same values
(a == b)
The result of the above boolean expression will be true if a and b share
the same memory address (and, therefore, reference the same array), and
false otherwise
In the same way that an equals method can be defined for a class, an
equalsArray method can be defined for a type of array
This is how two arrays must be tested to see if they contain the same
elements
The following method tests two integer arrays to see if they contain the
same integer values
public static boolean equalsArray(int[] a, int[] b)
{
if (a.length != b.length) return false;
else
{
int i = 0;
while (i < a.length)
{
if (a[i] != b[i])
return false;
i++;
}
}
return true;
}
Partially Filled Arrays
A variable can be used to keep track of how many elements are currently stored
in an array
For example, given the variable count, the elements of the array
someArray will range from positions someArray[0] through
someArray[count – 1]
Note that the variable count will be used to process the partially filled array
instead of someArray.length
Note also that this variable (count) must be an argument to any method
that manipulates the partially filled array
Accessor Methods Need Not Simply Return Instance Variables
When an instance variable names an array, it is not always necessary to provide
an accessor method that returns the contents of the entire array
Instead, other accessor methods that return a variety of information about the
array and its elements may be sufficient
The "for each" Loop
Although an ordinary for loop cannot cycle through the elements of a
collection class, an enhanced for loop can cycle through the elements of an
array
The general syntax for a for-each loop statement used with an array is
for (ArrayBaseType VariableName : ArrayName)
Statement
The above for-each line should be read as "for each VariableName in
ArrayName do the following:"
Note that VariableName must be declared within the for-each loop, not
before
Note also that a colon (not a semicolon) is used after VariableName
The for-each loop can make code cleaner and less error prone
If the indexed variable in a for loop is used only as a way to cycle through the
elements, then it would be preferable to change it to a for-each loop
For example:
for (int i = 0; i < a.length; i++)
a[i] = 0.0;
Can be changed to:
for (double element : a)
element = 0.0;
Note that the for-each syntax is simpler and quite easy to understand
Privacy Leaks with Array Instance Variables
If an accessor method does return the contents of an array, special care must
be taken
Just as when an accessor returns a reference to any private object
public double[] getArray()
{
return anArray;//BAD!
}
The example above will result in a privacy leak
The previous accessor method would simply return a reference to the array
anArray itself
Instead, an accessor method should return a reference to a deep copy of
the private array object
Below, both a and count are instance variables of the class containing
the getArray method
public double[] getArray()
{
double[] temp = new double[count];
for (int i = 0; i < count; i++)
temp[i] = a[i];
return temp
}
If a private instance variable is an array that has a class as its base type, then
copies must be made of each class object in the array when the array is copied:
public ClassType[] getArray()
{
ClassType[] temp = new ClassType[count];
for (int i = 0; i < count; i++)
temp[i] = new ClassType(someArray[i]);
return temp;
}
Sorting an Array
A sort method takes in an array parameter a, and rearranges the elements in a,
so that after the method call is finished, the elements of a are sorted in
ascending order
A selection sort accomplishes this by using the following algorithm:
for (int index = 0; index < count; index++)
Place the indexth smallest element in
a[index]
Selection Sort Class
public static void sort(double[] a, int count)
{
int index, indexOfNextSmallest;
for (index = 0; index < count - 1; index++)
{//Place the correct value in a[index]:
indexOfNextSmallest =
indexOfSmallest(index, a, count);
interchange(index,indexOfNextSmallest, a);
//a[0]<=a[1]<=...<=a[index] and these are
//the smallest of the original array
//elements. The remaining positions contain
//the rest of the original array elements.
}
}
/**
Returns the index of the smallest value among
a[startIndex], a[startIndex+1], ...
a[numberUsed - 1]
*/
private static int indexOfSmallest(int
startIndex, double[] a, int count)
{
double min = a[startIndex];
int indexOfMin = startIndex;
int index;
for (index = startIndex + 1;
index < count; index++)
if (a[index] < min)
{
min = a[index];
indexOfMin = index;
//min is smallest of a[startIndex] through
//a[index]
}
return indexOfMin;
}
/**
Precondition: i and j are legal indices for
the array a.
Postcondition: Values of a[i] and a[j] have
been interchanged.
*/
private static void interchange(int i, int j,
double[] a)
{
double temp;
temp = a[i];
a[i] = a[j];
a[j] = temp; //original value of a[i]
}
}
Enumerated Types Usage
An enumerated type is a type in which all the values are given in a (typically)
short list
The definition of an enumerated type is normally placed outside of all methods
in the same place that named constants are defined:
enum TypeName {VALUE_1, VALUE_2, …, VALUE_N};
Note that a value of an enumerated type is a kind of named constant and
so, by convention, is spelled with all uppercase letters
As with any other type, variables can be declared of an enumerated type
Given the following definition of an enumerated type:
enum WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY};
A variable of this type can be declared as follows:
WorkDay meetingDay, availableDay;
The value of a variable of this type can be set to one of the values listed in
the definition of the type, or else to the special value null:
meetingDay = WorkDay.THURSDAY;
availableDay = null;
Just like other types, variable of this type can be declared and initialized at the
same time:
WorkDay meetingDay = WorkDay.THURSDAY;
Note that the value of an enumerated type must be prefaced with the
name of the type
The value of a variable or constant of an enumerated type can be output
using println
The code:
System.out.println(meetingDay);
Will produce the following output:
THURSDAY
As will the code:
System.out.println(WorkDay.THURSDAY);
Note that the type name WorkDay is not output
Although they may look like String values, values of an enumerated type are
not String values
However, they can be used for tasks which could be done by String values and,
in some cases, work better
Using a String variable allows the possibility of setting the variable to a
nonsense value
Using an enumerated type variable constrains the possible values for that
variable
An error message will result if an attempt is made to give an enumerated
type variable a value that is not defined for its type
Two variables or constants of an enumerated type can be compared using the
equals method or the == operator
However, the == operator has a nicer syntax
if (meetingDay == availableDay)
System.out.println("Meeting will be on schedule.");
if (meetingDay == WorkDay.THURSDAY)
System.out.println("Long weekend!);
Multidimensional Arrays
It is sometimes useful to have an array with more than one index
Multidimensional arrays are declared and created in basically the same way as
one-dimensional arrays
You simply use as many square brackets as there are indices
Each index must be enclosed in its own brackets
double[][]table = new double[100][10];
int[][][] figure = new int[10][20][30];
Person[][] = new Person[10][100];
Multidimensional arrays may have any number of indices, but perhaps the most
common number is two
Two-dimensional array can be visualized as a two-dimensional display with
the first index giving the row, and the second index giving the column
char[][] a = new char[5][12];
Note that, like a one-dimensional array, each element of a
multidimensional array is just a variable of the base type (in this case, char)
In Java, a two-dimensional array, such as a, is actually an array of arrays
The array a contains a reference to a one-dimensional array of size 5 with a
base type of char[]
Each indexed variable (a[0], a[1], etc.) contains a reference to a onedimensional array of size 12, also with a base type of char[]
A three-dimensional array is an array of arrays of arrays, and so forth for higher
dimensions
Using the length Instance Variable
char[][] page = new char[30][100];
The instance variable length does not give the total number of indexed
variables in a two-dimensional array
Because a two-dimensional array is actually an array of arrays, the instance
variable length gives the number of first indices (or "rows") in the array
page.length is equal to 30
For the same reason, the number of second indices (or "columns") for a
given "row" is given by referencing length for that "row" variable
page[0].length is equal to 100
The following program demonstrates how a nested for loop can be used to
process a two-dimensional array
Note how each length instance variable is used
int row, column;
for (row = 0; row < page.length; row++)
for (column = 0; column < page[row].length;
column++)
page[row][column] = 'Z';
Ragged Arrays
Each row in a two-dimensional array need not have the same number of
elements
Different rows can have different numbers of columns
An array that has a different number of elements per row it is called a ragged
array
double[][] a = new double[3][5];
The above line is equivalent to the following:
double [][] a;
a = new double[3][]; //Note below
a[0] = new double[5];
a[1] = new double[5];
a[2] = new double[5];
Note that the second line makes a the name of an array with room for 3
entries, each of which can be an array of doubles that can be of any length
The next 3 lines each create an array of doubles of size 5
double [][] a;
a = new double[3][];
Since the above line does not specify the size of a[0], a[1], or a[2], each could
be made a different size instead:
a[0] = new double[5];
a[1] = new double[10];
a[2] = new double[4];
CSC1016 Lecture 20
Topic: Chapter 5 - Defining Classes II
Course: CSC1016S
Date: 11/09/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
Prac Test 1 third sitting will be taking place next week
The prac test 1 mark will be capped at 70%, so anyone who obtained 70% or
more in the previous sittings should not participate
This week's quiz will cover static and references
For assignment 7, submit UML diagram as a PDF ( You can use any online
website to design)
Using and Misusing References
When adding the private modifier to a primitive type instance variable, it will
prevent privacy leaks, but not so for class type instance variables
A statement that is always true for every object of the class is called a class
invariant
A class invariant can help to define a class in a consistent and organized
way
Copy Constructors
A copy constructor is a constructor with a single argument of the same type as
the class
The copy constructor should create an object that is a separate, independent
object, but with the instance variables set so that it is an exact copy of the
argument object
Copy Constructor for a Class with Primitive Type Instance Variables
code sample of safe copy constructor:
public Person(Person original){
if (original == null){
System.out.println("Fatal error.");
System.exit(0);
}
name = original.name;
born = new Date(original.born);
if (original.died == null)
died = null;
else
died = new Date(original.died);
}
This creates a new class instance, but with a difference reference location to the
original class
It ensures that changing the instance variables of the copy constructor will not
affect the original class values
Mutable and Immutable Classes
A class that contains no methods (other than constructors) that change any of
the data in an object of the class is called an immutable class
Objects of such a class are called immutable objects
It is perfectly safe to return a reference to an immutable object because the
object cannot be changed in any way
The String class is an immutable class
A class that contains public mutator methods or other public methods that can
change the data in its objects is called a mutable class, and its objects are called
mutable objects
Never write a method that returns a mutable object
Instead, use a copy constructor to return a reference to a completely
independent copy of the mutable object
Deep Copy Versus Shallow Copy
A deep copy of an object is a copy that, with one exception, has no references
in common with the original
Exception: References to immutable objects are allowed to be shared
A shallow copy of an object is a copy that has references in common with the
original
This type of copy can cause dangerous privacy leaks in a program
Introduction to javadoc
Unlike a language such as C++, Java places both the interface and the
implementation of a class in the same file
However, Java has a program called javadoc that automatically extracts the
interface from a class definition and produces documentation
This information is presented in HTML format, and can be viewed with a
Web browser
If a class is correctly commented, a programmer need only refer to this API
(Application Programming Interface) documentation in order to use the
class
javadoc can obtain documentation for anything from a single class to an
entire package
CSC1016S Lecture 19
Topic: Chapter 5: Defining Classes II
Course: CSC1016S
Date: 30/08/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
No lecture this Friday
Wrapper Classes
Wrapper classes provide a class type corresponding to each of the primitive
types
– This makes it possible to have class types that behave somewhat like primitive
types
– The wrapper classes for the primitive types byte, short, long, float, double,
and char are (in order) Byte, Short, Long, Float, Double, and Character
Wrapper classes also contain a number of useful predefined constants and
static methods
Boxing: the process of going from a value of a primitive type to an object of its
wrapper class
To convert a primitive value to an "equivalent" class type value, create an object
of the corresponding wrapper class using the primitive value as an argument
The new object will contain an instance variable that stores a copy of the
primitive value
Unlike most other classes, a wrapper class does not have a no-argument
constructor
Integer integerObject = new Integer(42);
Unboxing: the process of going from an object of a wrapper class to the
corresponding value of a primitive type
The methods for converting an object from the wrapper classes Byte, Short,
Integer, Long, Float, Double, and Character to their corresponding primitive
type are (in order) byteValue, shortValue, intValue, longValue, floatValue,
doubleValue, and charValue
None of these methods take an argument
int i = integerObject.intValue();
Automatic Boxing and Unboxing
• Starting with version 5.0, Java can automatically do boxing and unboxing
• Instead of creating a wrapper class object using the new operation (as shown
before), it can be done as an automatic type cast:
Integer integerObject = 42;
Instead of having to invoke the appropriate method (such as intValue,
doubleValue, charValue, etc.) in order to convert from an object of a wrapper
class to a value of its associated primitive type, the primitive value can be
recovered automatically
int i = integerObject;
Constants and Static Methods in Wrapper Classes
Wrapper classes include useful constants that provide the largest and smallest
values for any of the primitive number types
For example, Integer.MAX_VALUE, Integer.MIN_VALUE, Double.MAX_VALUE,
Double.MIN_VALUE, etc.
The Boolean class has names for two constants of type Boolean
Boolean.TRUE and Boolean.FALSE are the Boolean objects that correspond to
the values true and false of the primitive type boolean
Wrapper classes have static methods that convert a correctly formed string
representation of a number to the number of a given type
The methods Integer.parseInt, Long.parseLong, Float.parseFloat, and
Double.parseDouble do this for the primitive types (in order) int, long, float,
and double
Wrapper classes also have static methods that convert from a numeric value to
a string representation of the value For example, the expression
Double.toString(123.99); returns the string value "123.99"
The Character class contains a number of static methods that are useful for
string processing
Variables and Memory
A computer has two forms of memory
Secondary memory is used to hold files for "permanent" storage
Main memory is used by a computer when it is running a program
Values stored in a program's variables are kept in main memory
Main memory consists of a long list of numbered locations called bytes
Each byte contains eight bits: eight 0 or 1 digits
The number that identifies a byte is called its address
A data item can be stored in one (or more) of these bytes
The address of the byte is used to find the data item when needed
Values of most data types require more than one byte of storage
Several adjacent bytes are then used to hold the data item
The entire chunk of memory that holds the data is called its memory
location
The address of the first byte of this memory location is used as the address
for the data item
A computer's main memory can be thought of as a long list of memory
locations of varying sizes
References
Every variable is implemented as a location in computer memory
When the variable is a primitive type, the value of the variable is stored in the
memory location assigned to the variable
Each primitive type always require the same amount of memory to store its
values
When the variable is a class type, only the memory address (or reference) where
its object is located is stored in the memory location assigned to the variable
The object named by the variable is stored in some other location in
memory
Like primitives, the value of a class variable is a fixed size
Unlike primitives, the value of a class variable is a memory address or
reference
The object, whose address is stored in the variable, can be of any size
Two reference variables can contain the same reference, and therefore name
the same object
The assignment operator sets the reference (memory address) of one class
type variable equal to that of another
Any change to the object named by one of theses variables will produce a
change to the object named by the other variable, since they are the same
object
variable2 = variable1;
Class Parameters
All parameters in Java are call-by-value parameters
A parameter is a local variable that is set equal to the value of its argument
Therefore, any change to the value of the parameter cannot change the
value of its argument
Class type parameters appear to behave differently from primitive type
parameters
They appear to behave in a way similar to parameters in languages that
have the call-by-reference parameter passing mechanism
The value plugged into a class type parameter is a reference (memory address)
Therefore, the parameter becomes another name for the argument
Any change made to the object named by the parameter (i.e., changes
made to the values of its instance variables) will be made to the object
named by the argument, because they are the same object
Note that, because it still is a call-by-value parameter, any change made to
the class type parameter itself (i.e., its address) will not change its argument
(the reference or memory address)
Differences Between Primitive and Class-Type Parameters
A method cannot change the value of a variable of a primitive type that is an
argument to the method
In contrast, a method can change the values of the instance variables of a class
type that is an argument to the method
Pitfall: Use of = and == with Variables of a Class Type
Used with variables of a class type, the assignment operator (=) produces two
variables that name the same object
This is very different from how it behaves with primitive type variables
The test for equality (==) also behaves differently for class type variables
The == operator only checks that two class type variables have the same
memory address
Unlike the equals method, it does not check that their instance variables
have the same values
Two objects in two different locations whose instance variables have exactly
the same values would still test as being "not equal"
ToyClass variable1 = new ToyClass("Chiana", 3),
variable2 = new ToyClass("Chiana", 3);
if (variable1 == variable2)
System.out.println("Equal using ==");
else
System.out.println("Not equal using ==");
Instead use an equals
public boolean equals(ToyClass otherObject)
{
return ((name.equals(otherObject.name)) && (number ==
otherObject.number));
}
The Constant null
null is a special constant that may be assigned to a variable of any class type
YourClass yourObject = null;
It is used to indicate that the variable has no "real value"
It is often used in constructors to initialize class type instance variables
when there is no obvious object to use
null is not an object: It is, rather, a kind of "placeholder" for a reference that
does not name any memory location
Because it is like a memory address, use == or != (instead of equals) to test
if a class variable contains null
if (yourObject == null) ...
Pitfall: Null Pointer Exception
Even though a class variable can be initialized to null, this does not mean that
null is an object
null is only a placeholder for an object
A method cannot be invoked using a variable that is initialized to null
The calling object that must invoke a method does not exist
Any attempt to do this will result in a "Null Pointer Exception" error message
For example, if the class variable has not been initialized at all (and is not
assigned to null), the results will be the same
The new Operator and Anonymous Objects
The new operator invokes a constructor which initializes an object, and returns
a reference to the location in memory of the object created
This reference can be assigned to a variable of the object's class type
Sometimes the object created is used as an argument to a method, and never
used again
In this case, the object need not be assigned to a variable, i.e., given a
name
An object whose reference is not assigned to a variable is called an anonymous
object
Using and Misusing References
When writing a program, it is very important to insure that private instance
variables remain truly private
For a primitive type instance variable, just adding the private modifier to its
declaration should insure that there will be no privacy leaks
For a class type instance variable, however, adding the private modifier alone is
not sufficient
Designing A Person Class: Instance Variables
A simple Person class could contain instance variables representing a person's
name, the date on which they were born, and the date on which they died
These instance variables would all be class types: name of type String, and two
dates of type Date
As a first line of defense for privacy, each of the instance variables would be
declared private
public class Person
{
private String name;//String is an immutable (original String values can not be
changed)
private Date born;
private Date died; //null is still alive ...
SIPP Lecture 06
Topic: Introduction to values & Analytical Tools
Course: CSC1016S
Date: 31/08/2023
Professor/Speaker: Maria Keet
Summary
INTRODUCTION TO VALUES
Are Computer Ethics Special?
Are computer ethics different to those that came before?
No, since all fields have similar problems and issues.
Yes, since there are issues specific to computers such as the precise nature
of programming, autonomous action, etc.
What is it about computers that make the computer environment
different?
Speed: Computers are able to do things faster than ever before
data mining (only viable with computers)
Storage and accessibility of data: Vast amount of data can be stored and easily
accessible for processing.
Big Data
Concept of a program: How should one treat a computer program?
Is it a property or an idea or a process?
Is it something that may be copyrighted or patented? [see video]
Breadth of Distribution: IT has presented consumers with new channel of
distribution
Faster, easier
not as regulated internationally
Traditionalist Approach
Take traditional moral norm and principles; then apply to new situation
Problems with Traditionalist Approach?
Oversimplifies
Implies a routine way of dealing with ALL problems
Computing process is fluid – technology is changing
Different writers use different analogies
Internet – a network of highways (tolled or open?)
Internet – postal service (priority mail?)
Internet – a shopping mall
Different analogies give different solutions
Need to argue also why the analogy holds, or why one is better than
another
Filling the Policy Vacuum
Takes a long time for the ethical framework to be developed for an innovation
However: technology itself evolves (much) more quickly
The framework should precede the law
Appropriate laws are the best way to fill a policy vacuum
takes time.
Effective ways of filling the gap:
Personal policies
Company (but see paper on ‘finders keepers, losers weepers’)
Social conventions in society can often effectively fill the gap and provide a
framework for eventually creating laws (e.g., Free Software Foundation,
creative commons)
ANALYTICAL TOOLS
Critical Reasoning and Logical Arguments
Critical reasoning is a branch of informal logic.
Critical reasoning tools, especially argument analysis, can help us to resolve
many of the disputes in computer ethics.
A logical argument, or argument, is a form of reasoning comprising various
claims, or statements (or sentences).
(Logical) Arguments
A set of statements such that:
One of them is being said to be true (conclusion)
The other(s) (called premises) are being offered as reasons for accepting
('believing') the truth of the one conclusion.
An argument:
It is Monday, it always rains on the weekend in Cape Town, so it was raining
on the past couple of days.
Ice cream contains a lot of sugar. Sugar is unhealthy. Therefore eating ice
cream is unhealthy.
Arguments and Assertions I
An argument is a set of statements, one of which is being asserted
An assertion is a single statement (possibly complex) that is being stated as a
fact
Which of the following sentences are assertions?
1. It is very dry //assertion
2. Is it very dry?
3. Turn off the water sprinkler!
4. If it is very dry there will be water restrictions. //assertion
Arguments and Assertions II
Assertions are either true or false
but arguments are neither true nor false
Arguments are either ‘good’ or ‘bad’
How to specify ‘good’/’bad’?
Deductive Arguments
Deductive arguments are such that if their premises are true then the truth of
their conclusion is guaranteed
A deductive argument is either
valid (and gives us certainty)
or invalid and says nothing.
Structure:
All A are B
a is a A
Therefore a is B
For example:
All penguins are black and white
Penny is a penguin
Therefore Penny is black and white
Or:
All rockdassies are brown
Charlie is a rockdassie
Therefore Charlie is brown
Inductive Arguments
Inductive arguments are such that the truth of their premises makes the
conclusion more probably true.
Inductive arguments can be either weak or strong.
their conclusions can be slightly more likely to be true
or much more likely to be true
Example of a strong inductive argument:
The sun has risen every day for millions of years
Therefore the sun will rise tomorrow
Example of a weak inductive argument:
It has been raining for the past couple of days
Therefore it will rain today
CSC1016S Lecture 18
Topic: Chapter 5: Defining Classes II
Course: CSC1016S
Date: 29/08/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
Get to test venue at least 10 minutes before starting time
Make sure to bring phone into Scilabs in order to verify account
Download Microsoft Authentication for easier verification process
CHAPTER 5: Defining Classes II
Object variables store the reference to where the actual object is, in memory
e.g Student x = new Student();// x will store the reference memory of the actual
object
Static Variable
Static is used to access the actual memory location
A static method can only access static variables (i.e. can not access instance
variables)
A static method belongs to the class, whereas instance variables belong to an
instance of the class
Instance variable can not access static variable directly
Static variable can be declared and initialized at the same time
example of static variable: private static int myStaticVariable = 0;
A static variable is automatically initialized to the default value, unless initialized
by programmer
Static variables should always be private, unless it is also defined constant
The value of a static defined constant can not be altered therefore it is safe to
make it public
In addition a static constant variable should be final, e.g. public static final
double PI =3.142
Static Method
String[]args is used when you run a program from a command line
A static method that can be used without a calling object
A static method still belongs to a class, and its definition is given inside the
class defining
e.g public static returnType myMethod(parameters){body}
Static methods are invoked using the class name in place of a calling object
returnValue = MyClass.myMethod(argument)
Pitfall( or restriction):
Static methods can only refer( or call) to static variables
A static method has no this, so it can not use instance variables or instance
methods that has an implicit ot explicit this
A static method can invoke another static method
Tip: You Can Put a main In Any Class
Although the main method is often used in a separate class, it can be used to
turn the class into a program
If you print object variable, by default it will call upon the toString()
Return type can not be overloaded, only method name can be overloaded
Wrapper Class
Wrapper classes provide a class type corresponding to each of the primitive
types
This makes it possible to have class types that behave somewhat like
primitive types
The wrapper classes for the primitive types byte, short, long, float, double
and char are (in order) Byte, Short, Long, Double and Character
Boxing: the process of going from a value of a primitive type to object
e.g Integer integerObject = 42;
CSC1016S Lecture 17
Topic: UML Class Diagrams
Course: CSC1016S
Date: 28/08/2023
Professor/Speaker: Aslam Safla
Summary
Announcements
Prac Test 1 second sitting will be happening this week during the normal prac
sessions
Quiz 3 will be covering Chapter 4(past 3 weeks)
First 30 minutes will be alloted to quiz then after prac test 1(must use Scilab A)
Sign ups for Theory test 1 will be closing tommorrow
UML Class Diagrams:
UML Class diagrams.pdf
2 MB
CHAPTER 5
Static methods
A static method is one that can be used without calling object
A static method belongs to a class and its definition is given inside class
definition
Use keyword static to define static method (or variable)
Static methods are invoked using the name in place of calling object (e.g.
returnValue = MyClass.myMethod(argument);)
CSC1016S Lecture 16
CSC1016S Lecture 16.pdf
68 kB
CSC1016 Lecture 15
CSC1016 Lecture 15.pdf
2 MB
CSC1016S Lecture 14
CSC1016S Lecture 14.pdf
CSC1016S Lecture 13
83 kB
CSC1016S Lecture 13.pdf
124 kB
CSC1016S Lecture 12
CSC1016S Lecture 12.pdf
100 kB
SIPP Lecture 04
SIPP Lecture 04.pdf
130 kB
CSC1016S Lecture 11
CSC1016S Lecture 11.pdf
104 kB
CSC1016S Lecture 10
CSC1016S Lecture 10.pdf
98 kB
CSC1016S Lecture 08
CSC1016S Lecture 08.pdf
106 kB
SIPP Lecture 03
SIPP Lecture 03.pdf
89 kB
CSC1016S Lecture 07-07082023
CSC1016S Lecture 07-07082023.pdf
115 kB
SIPP Lecture 02
SIPP Lecture 02.pdf
86 kB
SIPP Lecture 01
SIPP Lecture 01.pdf
67 kB
CSC1016S Lecture 06
CSC1016S Lecture 06.pdf
106 kB
CSC1016S Lecture 05
CSC1016S Lecture 05.pdf
113 kB
CSC1016S Lecture 04
CSC1016S Lecture 04.pdf
108 kB
CSC1016S Lecture 03
CSC1016S Lecture 03.pdf
121 kB
CSC1016S Lecture 02
CSC1016S Lecture 02.pdf
110 kB
CSC1016S Lecture 01
CSC1016S Lecture 01.pdf
SIPP Lecture 05
57 kB
SIPP Lecture 05.pdf
90 kB
CSC1016S Lecture 09
Topic: Defining Classes I
Course: CSC1016S
Date: 14/08/2023
Professor/Speaker: Safla Aslam
Summary
ANNOUNCEMENTS
Starting from this week, we'll be having Friday lectures from 11h00-11h45
(LS2A) and 12h00-12h45 (New Lecture Theatre)
Introductions to assignments will be done on the Friday lectures from now on
ASSIGNMENT 4 INTRO
Unit testing is the most basic form of testing methods
Question 1 deals with unit testing
Check how to use JUnit in JGRASP by following this pathway:
Amathuba>CSC1016S>OOP in Java>Section 4>Using JUnit in JGRASP
After configuring JUnit, check top tabs for 'create JUnit' and click it to start new
JUnit file
More to be discussed on Friday
CHAPTER 4
DEFINING CLASSES I
Instance Variables and Methods
public void myMethod(Parameter_goes_here)
public : type of method (public, protected, private etc.)
void : type of value returned (String, int, double etc.)
myMethod : name of method
In Java we have two types of methods. Namely the void method and non-void
method
At the end of every non-void method, the return statement must be included
We can have any number of conditional return statements, but only one will be
returned by the method
void methods have no return statements, they only execute the specified action
within the method body
The 'main' function is a void method
Local variable: A variable declared within a method (i.e. a variable that exists
only within a method, as opposed to instance variables)
Java does not have global variables
Download