SlideShare a Scribd company logo
1 of 36
Download to read offline
Lecture 4:
Make your own class
Outline
Phase 1
▪ Creating a class
▪ Get and set methods
▪ Constructors
▪ Private and public
▪ Encapsulation
Recall…
▪ So far we
have been
dealing with
a simple
template.
– Some import
statements
– Main class
▪ Attributes
▪ Methods
(one must be
main)
import <something>;
public class L3{
//<some attributes>
public static void main(String[] args) {
//<some stuff>
}
}
Recall…
▪ In this lecture, we will be shifting between
– Writing a class
– Creating objects using that class in the main method
▪ Make sure you know which one we are in.
Writing your own class
▪ Not necessary but recommended that each class gets
its own file – name the .java file after the class.
▪ Remember that classes are helpful in creating
programming versions of real-world things.
▪ Lets make some classes for a University program. What
objects would be useful?
– Students
– Staff
– Courses
– Degrees
– …
Writing your own class
▪ Let’s start with Student:
▪ We need some attributes and
methods.
▪ For now, some basic attributes:
– firstName, lastName
public class Student {
String firstName;
String lastName;
//Methods
}
Writing your own class
▪ Now in the main method, I
could create an object from this
class and access its attributes:
public class L4 {
public static void main(String[] args) {
Student s = new Student();
s.firstName = "Jonathan";
s.lastName = "Parker";
}
}
But…
Accessor and Mutator Methods
▪ Accessor methods return the value of a variable.
▪ Typically named with “get” in front of the variable name
▪ Mutator methods set the value of a variable.
▪ Typically named with “set” in front of variable name
A good practice is to prevent the user from accessing or
changing attributes directly, but instead to do so through
accessor and mutator methods
Accessor and Mutator Methods
▪ Accessor method for firstName.
– No input argument
– return a String type
– return value of firstName
▪ Mutator method for firstName.
– Must take new value for firstName as
input argument
– No return type
– No return value
public class Student {
String firstName;
String lastName;
String getFirstName(){
return firstName;
}
void setFirstName(String s){
firstName = s;
}
String getLastName(){
return lastName;
}
void setLastName(String s){
lastName = s;
}
}
▪ The reason for doing this
will become clear later on.
▪ It helps control which
classes have access to
these variables.
public class Student {
String firstName;
String lastName;
String getFirstName(){
return firstName;
}
void setFirstName(String s){
firstName = s;
}
String getLastName(){
return lastName;
}
void setLastName(String s){
lastName = s;
}
}
Accessor and Mutator Methods
Constructor Methods
▪ Useful for initializing variables
▪ Constructors are named after the class
▪ Constructors do not return anything, no return
type or return statement
▪ Constructors are run immediately after an object is
created.
Constructor method
A method executed when a new instance of a class is
created.
Constructor Methods
Constructor method:
▪ We can pass parameters to the constructor.
▪ We can use these parameters to initialize some
variables, or initialization can be hard-coded.
▪ Say, default first name is “Jonathan”, default last name
is “Parker”.
▪ If we don’t define a constructor, then the compiler
creates a default constructor, which is blank.
Constructor Methods
▪ Constructor method:
public class Student {
String firstName;
String lastName;
Student(String defaultFirstName, String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
}
//Other methods
}
Same
name
Constructor Methods
…
Student(){
firstName = "John";
lastName = "Smith";
}
…
…
Student(String defaultFirstName,
String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
}
…
Constructor taking arguments
to set default values.
Constructor with hard coded
default values.
Constructor Methods
▪ Now we can create an object
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
}
}
Accessor and Mutator Methods
▪ We can use the objects methods.
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
System.out.println("First Name is " + s.getFirstName());
System.out.println("Last Name is " + s.getLastName());
}
}
First Name is Jonathan
Last Name is Parker
Accessor and Mutator Methods
▪ We can use the objects methods.
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
s.setFirstName("Harry");
s.setLastName("Potter");
System.out.println("First Name is " + s.getFirstName());
System.out.println("Last Name is " + s.getLastName());
}
}
First Name is Harry
Last Name is Potter
Writing your own class
▪ At the moment, our Student class doesn’t do much…
▪ Let’s add an attribute: an array that contains test marks
public class Student {
…
float[] testMarks;
…
Student(String defaultFirstName, String defaultLastName){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[5];
}
}
Writing your own class
▪ When is the array created?
▪ We only create the array at the creation of the object - we can
get the desired size as an input to the constructor.
public class Student {…
float[] testMarks;
…
Student(String defaultFirstName, String defaultLastName , int NoTests){
firstName = defaultFirstName;
lastName = defaultLastName;
testMarks = new float[NoTests];
}
}
Writing your own class
▪ We can give get and set methods for this array.
▪ There are more sophisticated ways of interacted with
arrays which we will see later.
void setTestMark(float mark, int id){
testMarks[id] = mark;
}
float getTestMark(int id){
return testMarks[id];
}
Writing your own class
▪ We can also write a method that displays all the marks.
void displayAllTestMarks() {
System.out.println();
for (int i = 0; i < testMarks.length;i++) {
System.out.printf("Test " + i + ": %.1fn",testMarks[i]);
}
}
Writing your own class
Exercise:
▪ Write a method that gives the maximum mark for the tests
▪ Write a method that gives the minimum mark for the tests
▪ Write a method that gives the average mark for the tests
Writing your own class
Exercise:
▪ Write a method that gives the maximum mark for the tests
– Initialise the maximum mark to minimum possible value
– Loop through all the marks  if mark > max_mark then set max_mark =
mark
▪ Write a method that gives the minimum mark for the tests
– Initialise the minimum mark to maximum possible value
– Loop through all the marks  if mark < min_mark then set min_mark =
mark
▪ Write a method that gives the average mark for the tests
– Loop through all the marks, add them up
– After the loop, divide the marks by the number of marks
Writing your own class
float returnMaxMark() {
float max = 0;
for (float t : testMarks) {
max = t > max ? t : max;
}
return max;
}
float returnMinMark() {
float min = 100;
for (float t : testMarks) {
min = t < min ? t : min;
}
return min;
}
float returnAveMark() {
float sum = 0, ave = 0;
for (float t : testMarks) {
sum += t;
}
ave = sum/testMarks.length;
return ave;
}
Methods calling methods
▪ Methods calling methods: methods of one object can call
methods of that same object.
▪ Example: if we want to display…
– the students name,
– with all the test marks
– and the max, min and average marks,
▪ …we can use some of the methods we wrote earlier.
Methods calling methods
▪ Note: we don’t need to use the dot notation i.e.
Student.displayAllTestMarks()
▪ Can just say displayAllTestMarks() – why can we do this?
void displayAllStats() {
System.out.println("Name: " + firstName +" " + lastName);
System.out.println();
displayAllTestMarks();
System.out.println();
System.out.printf("Average: %.1fn", returnAveMark());
System.out.printf("Maximum: %.1fn", returnMaxMark());
System.out.printf("Minimum: %.1fn", returnMinMark());
}
Writing your own class
▪ Summary so far:
– Created a class
– Given it some attributes
– Wrote methods to access and change these values
– Wrote a constructor to initialize the attributes
– Wrote methods that did stuff with these attributes
– Wrote a method that used another method
Accessibility Modifiers
▪ A private attribute can only be accessed by the methods
of that class or object.
▪ A private method can only be accessed by the methods
of that class or object.
▪ We can also modifier whole classes to be public or
private – more later.
Accessibility modifiers
Change what methods can access the members of a class
Accessibility Modifiers
▪ By default, members are public. Good practice to include
them anyway.
private String firstName;
private String lastName;
private float[] testMarks;
A common practice is to declare most or all attributes private
and then use the get and set methods to interact with the
attributes outside of the class.
Accessibility Modifiers
▪ Now, if we try to access the private attributes directly in
the main class, we won’t be able to:
public class L4 {
public static void main(String[] args) {
Student s = new Student("Jonathan", "Parker");
s.firstName = "Jonathan";
s.lastName = "Parker";
}
}
Will not compile
Accessibility Modifiers
▪ But accessing the private attributes directly from within
the same class will be fine:
public class Student {
void displayAllTestMarks() {
System.out.println();
for (int i = 0; i < testMarks.length;i++) {
System.out.printf("Test " + i + ": %.1fn",testMarks[i]);
}
}
}


Encapsulation
▪ It is a core tenet of object orientated programming.
▪ Why?
– Prevents the user of our class accessing information or functions
that they shouldn’t.
– Helps provide an extra layer of abstraction between what the
class does and how it does it.
Encapsulation
Information hiding – members of a class or object
are hidden from the outside.
Encapsulation
▪ Example: Imagine a class that controls the movement of
a humanoid robot.
▪ We want the robot to:
– Move forward
– Increase/decrease speed
– Change direction
▪ The way we implement these might be with methods:
– Take one step forward
– Increase/decrease speed of motor
– Change relative speed each leg
Encapsulation
▪ Example: But if we have changed our robot to one that
moves on wheels
▪ We still want the robot to:
– Move forward
– Increase/decrease speed
– Change direction
▪ But we now implement with different methods, such as:
– Rotate wheels at defined speed
– Increase/decrease speed of motor and/or change gears
– Change relative speed each wheel
same
different
Encapsulation
▪ We have separated the external methods and attributes
from the internal methods and attributes.
▪ This has allowed us to keep the external facing interface
the same, while changing how we have implemented its
functionality.
▪ We have changed how we do something, without
changing what we are doing.
▪ Allow for easier modification of code.
Summary
Summary so far
▪ Created a class
▪ Get and set methods
▪ Constructors
▪ Private and public modifiers
▪ Encapsulation

More Related Content

Similar to Lecture 4 part 1.pdf

03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdfParameshwar Maddela
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part IIIHari Christian
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
Assignment 7
Assignment 7Assignment 7
Assignment 7IIUM
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
02 java basics
02 java basics02 java basics
02 java basicsbsnl007
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Developing Applications for Android - Lecture#2
Developing Applications for Android - Lecture#2Developing Applications for Android - Lecture#2
Developing Applications for Android - Lecture#2Usman Chaudhry
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 

Similar to Lecture 4 part 1.pdf (20)

03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Lecture Notes
Lecture NotesLecture Notes
Lecture Notes
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Lecture 7.pdf
Lecture 7.pdfLecture 7.pdf
Lecture 7.pdf
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
02 java basics
02 java basics02 java basics
02 java basics
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Developing Applications for Android - Lecture#2
Developing Applications for Android - Lecture#2Developing Applications for Android - Lecture#2
Developing Applications for Android - Lecture#2
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 

More from SakhilejasonMsibi (7)

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Lecture 5.pdf
Lecture 5.pdfLecture 5.pdf
Lecture 5.pdf
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..MaherOthman7
 
engineering chemistry power point presentation
engineering chemistry  power point presentationengineering chemistry  power point presentation
engineering chemistry power point presentationsj9399037128
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfragupathi90
 
21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological universityMohd Saifudeen
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Studentskannan348865
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfEr.Sonali Nasikkar
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisDr.Costas Sachpazis
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxMustafa Ahmed
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New HorizonMorshed Ahmed Rahath
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...IJECEIAES
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxkalpana413121
 
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and ToolsMaximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Toolssoginsider
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxCHAIRMAN M
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
Software Engineering Practical File Front Pages.pdf
Software Engineering Practical File Front Pages.pdfSoftware Engineering Practical File Front Pages.pdf
Software Engineering Practical File Front Pages.pdfssuser5c9d4b1
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.benjamincojr
 
Artificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdfArtificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdfKira Dess
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdfAlexander Litvinenko
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptjigup7320
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxKarpagam Institute of Teechnology
 

Recently uploaded (20)

Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
 
engineering chemistry power point presentation
engineering chemistry  power point presentationengineering chemistry  power point presentation
engineering chemistry power point presentation
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university21scheme vtu syllabus of visveraya technological university
21scheme vtu syllabus of visveraya technological university
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdfInstruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
Instruct Nirmaana 24-Smart and Lean Construction Through Technology.pdf
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptx
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and ToolsMaximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
 
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptxSLIDESHARE PPT-DECISION MAKING METHODS.pptx
SLIDESHARE PPT-DECISION MAKING METHODS.pptx
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Software Engineering Practical File Front Pages.pdf
Software Engineering Practical File Front Pages.pdfSoftware Engineering Practical File Front Pages.pdf
Software Engineering Practical File Front Pages.pdf
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
 
Artificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdfArtificial intelligence presentation2-171219131633.pdf
Artificial intelligence presentation2-171219131633.pdf
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 

Lecture 4 part 1.pdf

  • 2. Outline Phase 1 ▪ Creating a class ▪ Get and set methods ▪ Constructors ▪ Private and public ▪ Encapsulation
  • 3. Recall… ▪ So far we have been dealing with a simple template. – Some import statements – Main class ▪ Attributes ▪ Methods (one must be main) import <something>; public class L3{ //<some attributes> public static void main(String[] args) { //<some stuff> } }
  • 4. Recall… ▪ In this lecture, we will be shifting between – Writing a class – Creating objects using that class in the main method ▪ Make sure you know which one we are in.
  • 5. Writing your own class ▪ Not necessary but recommended that each class gets its own file – name the .java file after the class. ▪ Remember that classes are helpful in creating programming versions of real-world things. ▪ Lets make some classes for a University program. What objects would be useful? – Students – Staff – Courses – Degrees – …
  • 6. Writing your own class ▪ Let’s start with Student: ▪ We need some attributes and methods. ▪ For now, some basic attributes: – firstName, lastName public class Student { String firstName; String lastName; //Methods }
  • 7. Writing your own class ▪ Now in the main method, I could create an object from this class and access its attributes: public class L4 { public static void main(String[] args) { Student s = new Student(); s.firstName = "Jonathan"; s.lastName = "Parker"; } } But…
  • 8. Accessor and Mutator Methods ▪ Accessor methods return the value of a variable. ▪ Typically named with “get” in front of the variable name ▪ Mutator methods set the value of a variable. ▪ Typically named with “set” in front of variable name A good practice is to prevent the user from accessing or changing attributes directly, but instead to do so through accessor and mutator methods
  • 9. Accessor and Mutator Methods ▪ Accessor method for firstName. – No input argument – return a String type – return value of firstName ▪ Mutator method for firstName. – Must take new value for firstName as input argument – No return type – No return value public class Student { String firstName; String lastName; String getFirstName(){ return firstName; } void setFirstName(String s){ firstName = s; } String getLastName(){ return lastName; } void setLastName(String s){ lastName = s; } }
  • 10. ▪ The reason for doing this will become clear later on. ▪ It helps control which classes have access to these variables. public class Student { String firstName; String lastName; String getFirstName(){ return firstName; } void setFirstName(String s){ firstName = s; } String getLastName(){ return lastName; } void setLastName(String s){ lastName = s; } } Accessor and Mutator Methods
  • 11. Constructor Methods ▪ Useful for initializing variables ▪ Constructors are named after the class ▪ Constructors do not return anything, no return type or return statement ▪ Constructors are run immediately after an object is created. Constructor method A method executed when a new instance of a class is created.
  • 12. Constructor Methods Constructor method: ▪ We can pass parameters to the constructor. ▪ We can use these parameters to initialize some variables, or initialization can be hard-coded. ▪ Say, default first name is “Jonathan”, default last name is “Parker”. ▪ If we don’t define a constructor, then the compiler creates a default constructor, which is blank.
  • 13. Constructor Methods ▪ Constructor method: public class Student { String firstName; String lastName; Student(String defaultFirstName, String defaultLastName){ firstName = defaultFirstName; lastName = defaultLastName; } //Other methods } Same name
  • 14. Constructor Methods … Student(){ firstName = "John"; lastName = "Smith"; } … … Student(String defaultFirstName, String defaultLastName){ firstName = defaultFirstName; lastName = defaultLastName; } … Constructor taking arguments to set default values. Constructor with hard coded default values.
  • 15. Constructor Methods ▪ Now we can create an object public class L4 { public static void main(String[] args) { Student s = new Student("Jonathan", "Parker"); } }
  • 16. Accessor and Mutator Methods ▪ We can use the objects methods. public class L4 { public static void main(String[] args) { Student s = new Student("Jonathan", "Parker"); System.out.println("First Name is " + s.getFirstName()); System.out.println("Last Name is " + s.getLastName()); } } First Name is Jonathan Last Name is Parker
  • 17. Accessor and Mutator Methods ▪ We can use the objects methods. public class L4 { public static void main(String[] args) { Student s = new Student("Jonathan", "Parker"); s.setFirstName("Harry"); s.setLastName("Potter"); System.out.println("First Name is " + s.getFirstName()); System.out.println("Last Name is " + s.getLastName()); } } First Name is Harry Last Name is Potter
  • 18. Writing your own class ▪ At the moment, our Student class doesn’t do much… ▪ Let’s add an attribute: an array that contains test marks public class Student { … float[] testMarks; … Student(String defaultFirstName, String defaultLastName){ firstName = defaultFirstName; lastName = defaultLastName; testMarks = new float[5]; } }
  • 19. Writing your own class ▪ When is the array created? ▪ We only create the array at the creation of the object - we can get the desired size as an input to the constructor. public class Student {… float[] testMarks; … Student(String defaultFirstName, String defaultLastName , int NoTests){ firstName = defaultFirstName; lastName = defaultLastName; testMarks = new float[NoTests]; } }
  • 20. Writing your own class ▪ We can give get and set methods for this array. ▪ There are more sophisticated ways of interacted with arrays which we will see later. void setTestMark(float mark, int id){ testMarks[id] = mark; } float getTestMark(int id){ return testMarks[id]; }
  • 21. Writing your own class ▪ We can also write a method that displays all the marks. void displayAllTestMarks() { System.out.println(); for (int i = 0; i < testMarks.length;i++) { System.out.printf("Test " + i + ": %.1fn",testMarks[i]); } }
  • 22. Writing your own class Exercise: ▪ Write a method that gives the maximum mark for the tests ▪ Write a method that gives the minimum mark for the tests ▪ Write a method that gives the average mark for the tests
  • 23. Writing your own class Exercise: ▪ Write a method that gives the maximum mark for the tests – Initialise the maximum mark to minimum possible value – Loop through all the marks  if mark > max_mark then set max_mark = mark ▪ Write a method that gives the minimum mark for the tests – Initialise the minimum mark to maximum possible value – Loop through all the marks  if mark < min_mark then set min_mark = mark ▪ Write a method that gives the average mark for the tests – Loop through all the marks, add them up – After the loop, divide the marks by the number of marks
  • 24. Writing your own class float returnMaxMark() { float max = 0; for (float t : testMarks) { max = t > max ? t : max; } return max; } float returnMinMark() { float min = 100; for (float t : testMarks) { min = t < min ? t : min; } return min; } float returnAveMark() { float sum = 0, ave = 0; for (float t : testMarks) { sum += t; } ave = sum/testMarks.length; return ave; }
  • 25. Methods calling methods ▪ Methods calling methods: methods of one object can call methods of that same object. ▪ Example: if we want to display… – the students name, – with all the test marks – and the max, min and average marks, ▪ …we can use some of the methods we wrote earlier.
  • 26. Methods calling methods ▪ Note: we don’t need to use the dot notation i.e. Student.displayAllTestMarks() ▪ Can just say displayAllTestMarks() – why can we do this? void displayAllStats() { System.out.println("Name: " + firstName +" " + lastName); System.out.println(); displayAllTestMarks(); System.out.println(); System.out.printf("Average: %.1fn", returnAveMark()); System.out.printf("Maximum: %.1fn", returnMaxMark()); System.out.printf("Minimum: %.1fn", returnMinMark()); }
  • 27. Writing your own class ▪ Summary so far: – Created a class – Given it some attributes – Wrote methods to access and change these values – Wrote a constructor to initialize the attributes – Wrote methods that did stuff with these attributes – Wrote a method that used another method
  • 28. Accessibility Modifiers ▪ A private attribute can only be accessed by the methods of that class or object. ▪ A private method can only be accessed by the methods of that class or object. ▪ We can also modifier whole classes to be public or private – more later. Accessibility modifiers Change what methods can access the members of a class
  • 29. Accessibility Modifiers ▪ By default, members are public. Good practice to include them anyway. private String firstName; private String lastName; private float[] testMarks; A common practice is to declare most or all attributes private and then use the get and set methods to interact with the attributes outside of the class.
  • 30. Accessibility Modifiers ▪ Now, if we try to access the private attributes directly in the main class, we won’t be able to: public class L4 { public static void main(String[] args) { Student s = new Student("Jonathan", "Parker"); s.firstName = "Jonathan"; s.lastName = "Parker"; } } Will not compile
  • 31. Accessibility Modifiers ▪ But accessing the private attributes directly from within the same class will be fine: public class Student { void displayAllTestMarks() { System.out.println(); for (int i = 0; i < testMarks.length;i++) { System.out.printf("Test " + i + ": %.1fn",testMarks[i]); } } }  
  • 32. Encapsulation ▪ It is a core tenet of object orientated programming. ▪ Why? – Prevents the user of our class accessing information or functions that they shouldn’t. – Helps provide an extra layer of abstraction between what the class does and how it does it. Encapsulation Information hiding – members of a class or object are hidden from the outside.
  • 33. Encapsulation ▪ Example: Imagine a class that controls the movement of a humanoid robot. ▪ We want the robot to: – Move forward – Increase/decrease speed – Change direction ▪ The way we implement these might be with methods: – Take one step forward – Increase/decrease speed of motor – Change relative speed each leg
  • 34. Encapsulation ▪ Example: But if we have changed our robot to one that moves on wheels ▪ We still want the robot to: – Move forward – Increase/decrease speed – Change direction ▪ But we now implement with different methods, such as: – Rotate wheels at defined speed – Increase/decrease speed of motor and/or change gears – Change relative speed each wheel same different
  • 35. Encapsulation ▪ We have separated the external methods and attributes from the internal methods and attributes. ▪ This has allowed us to keep the external facing interface the same, while changing how we have implemented its functionality. ▪ We have changed how we do something, without changing what we are doing. ▪ Allow for easier modification of code.
  • 36. Summary Summary so far ▪ Created a class ▪ Get and set methods ▪ Constructors ▪ Private and public modifiers ▪ Encapsulation