Download presentation
Presentation is loading. Please wait.
Published bySilvester Gordon Modified over 6 years ago
1
Software Development Java Classes and Methods
Computer Science 209 Software Development Java Classes and Methods
2
Objects, Classes, and Methods
There are no functions in Java, only methods There are instance methods and class methods Built-in classes include String, Math, and Arrays Classes in libraries include a host of collections, file streams, resources for GUIs, networks, concurrency, etc.
3
Example: A Student Class
A student has a name and a set of test scores The name can be accessed and reset Scores can be accessed and reset by position, counting from 1 The high score and the average score can be accessed Constructors and string representation are available
4
Default Instantiation and String Representation
Student s = new Student(); System.out.println(s); Name: Scores: Defaults are an empty name string and 3 scores of 0
5
User-Specified Instantiation and String Representation
Student s = new Student("Ken", 5); System.out.println(s); Name: Ken Scores: Defaults can be overridden with another constructor
6
Access and Mutate Student s = new Student("Ken", 5);
for (int i = 1; i <= 5; i++) // Set all scores to 100 s.setScore(i, 100); System.out.println("Average: " + s.getAverageScore()); System.out.println("High: " + s.getHighScore()); Average: 100.0 High:
7
Python Class Definition
class Student(object): # Class variable DEFAULT_NUM_SCORES = 3 # Constructor def __init__(self, nm = "", numScores = None): self.name = nm if numScores: self.scores = Array(numScores) else: self.scores = Array(Student.DEFAULT_NUM_SCORES) # String representation def __str__(self): result = "Name: " + self.name + "\nScores:\n" for score in self scores: result += str(score) + "\n" result += "Average: " + getAverage(); return result
8
Java Class Definition public class Student extends Object{ // Class variable static public final int DEFAULT_NUM_SCORES = 3; static variables hold data shared by all instances of the class final variables behave like constants Constants use all caps and underscores
9
Java Class Definition public class Student{ // Class variable static public final int DEFAULT_NUM_SCORES = 3; // Instance variables private String name; private int[] scores; Instance variables hold data that belong to each individual object Instance variables are declared at the same level as methods Instance variables are normally declared private
10
Java Class Definition Constructors can be chained
public class Student{ // Class variable static public final int DEFAULT_NUM_SCORES = 3; // Instance variables private String name; private int[] scores; // Constructors public Student(String nm, int numScores){ name = nm; scores = new int[numScores]; } public Student(){ this("", DEFAULT_NUM_SCORES); Constructors can be chained
11
Access Modifiers For now, all methods should be declared as public
For now, all instance variables should be declared as private For now, all class (static) variables should be declared as public final
12
Pubic, Private, Static, and Final
public – anyone can access the item private – access only within the class definition static – the item belongs to the class, not to its instances final – you can initialize but not reset the item
13
The toString Method // String representation public String toString(){ String str = "Name: " + name + "\nScores:\n"; for (int score : scores) str += score + "\n"; str += "Average: " + getAverage(); return str; } Java automatically runs toString on arguments to println
14
Accessor Methods Just observe state without changing it
public String getName(){ return name; } public int getScore(int i){ return scores[i - 1]; public int getNumScores(){ return scores.length; Just observe state without changing it
15
Mutator Methods Change the state! public void setName(String nm){
name = nm; } public void setScore(int i, int newScore){ scores[i - 1] = newScore; Change the state!
16
Mutator Methods Change the state!
public void setName(String nm){ name = nm; } public void setScore(int i, int newScore){ scores[i - 1] = newScore; Change the state! Because scores has been declared private, it can only be accessed or modified by running getScore or setScore (data encapsulation)
17
Equality public boolean equals(Object other){ if (this == other) return true; if (! (other instanceof Student)) return false; Student s = (Student) other; return this.name.equals(s.name); } The Object class is the root class in the Java class hierarchy. You can assign any object to a variable or parameter of type Object Check identity type structure
18
Comparisons and Ordering
public interface Comparable<T>{ // Returns 0 if receiver equals other // Returns < 0 if receiver is less than other // Returns > 0 if receiver is greater than other public int compareTo(T other); } public class Student implements Comparable<Student>{ public int compareTo(Student other){ return this.name.compareTo(other.name); } … More strict than equals; type errors are caught at compile time
19
Now Do Sorting and Searching
Student [] students = new Student[10]; // Add 10 Student objects to the array java.util.Arrays.sort(students); Student target = new Student("ken", 10)); int position = java.util.Arrays.binarySearch(students, target); The element type in the array must implement the Comparable interface
20
Preconditions Postconditions Exceptions Javadoc
For next time Preconditions Postconditions Exceptions Javadoc
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.