CSCI 1933 Lecture4
CSCI 1933 Lecture4
• Today:
• Finish arrays, Wrapper classes, Object-oriented
programming: composition, inheritance
• Announcements:
• Project 1 due tomorrow (Friday, 2/11, 7pm)
• Lab 3 due this Friday (last office hours)
• Midterm #1: February 24 (two weeks from
today)
Midterm 1
• Thursday, February 24, 6:30-8:30pm
• Closed book, closed computer
• You are allowed 1 page (8.5” x 11”)
(2 sides) of handwritten notes
return result;
}
Reminders about solving problems
with recursion
Recursive solution: an operation that can be defined in
terms of itself
– Solving a problem using recursion depends on solving
smaller occurrences of the same problem
return result;
}
double result;
if(x <= 1) { result=1;}
else {
result = x*recurseFactorial(x-1);
}
return result;
}
Review of variable scope
count++;
return result;
Code in main program:
} MyMath calculator = new MyMath();
calculator.linearFunction(10,0,1);
public double getNumCalls() { double sum=0;
return count; for(int i=1; i < 100; i++) {
} sum += calculator.factorial(i);
}
} System.out.println("NumCalls="+calculator.get
NumCalls());
Strings in Java
• Strings are another built-in class (java.lang
package)
• Strings are immutable—once they’re created,
they can’t be modified
• Otherwise, they’re just objects, like everything
else we’ve talked about
System.out.println(className);
What’s the right way to compare Strings?
• Strings are objects just like most other things we’ve covered
• They have a defined set of methods for interacting with them, e.g.
char charAt(int index)
Returns the char value at the specified index.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean equals(Object anObject)
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.
int length()
Returns the length of this string.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with
the given replacement.
String[] split(String regex)
Splits this string around matches of the given regular expression.
(Also compareToIgnoreCase() method – treats upper and lower case the same)
Searching within strings
• int indexOf(char c): finds first occurrence of character c
• Example:
String className = "UMN:CSCI:1933:Sec001";
StringTokenizer st = new Output:
StringTokenizer(className,":"); 1:UMN
2:CSCI
int count=1; 3:1933
while(st.hasMoreTokens()) {
4:Sec001
System.out.println(count+":"+st.nextToken());
count++;
}
Array declarations
• Declaration/initialization of arrays:
Primitives Arrays
int[] a = new int[]{23, 565, 21, 56, 22,1000,675, 123, 676, 87};
New material
Overview of today’s material
• Object-oriented programming:
- Composition
- inheritance
Arrays
Assignment operators
For array elements, "=" is a copy operation:
temperatures[monday] = temperatures[sunday];
Output:
Ashlee
Austin
String[] TAs ={“Ashlee",“Austin",“Alice",“Isaac"}; Alice
for (String curr : TAs) { Isaac
System.out.println(curr);
}
Output:
int[] intArray = {1,2,3,4}; 1
for(int curr : intArray) { 2
System.out.println(curr); 3
} 4
Passing arrays to functions
public static double calcMean(int[] a) {
double result=0;
return(result/a.length);
}
In main program:
int arr[] = {10, 90, 49, 2, 1, 5, 23};
System.out.println("Mean: "+calcMean(arr));
Passing arrays to functions (2)
public static void negateArray(int[] arr) {
for(int i=0; i < arr.length; i++) {
arr[i]=-arr[i];
}
In main program:
int arr[] = {10, 90, 49, 2, 1, 5, 23};
negateArray(arr);
System.out.println("Negated element: "+arr[0]);
return(newarr);
}
In main method:
int[] zeroArray = getZeros(10);
System.out.println("Length: "+zeroArray.length+",
first element: "+zeroArray[0]);
if(keyboard.hasNextInt()) {
circleArray[count++] = new Circle(0,0,keyboard.nextInt());
} else { break; }
}
What’s wrong with this code?
if(keyboard.hasNextInt()) {
circleArray[count++] = new Circle(0,0,keyboard.nextInt());
} else { break; }
}
Throws ArrayIndexOutOfBoundsException!
if(keyboard.hasNextInt()) {
circleArray[count++] = new
Circle(0,0,keyboard.nextInt());
} else { break; }
}
Exercise: Write a function called resize that can compact our array
Exercise
Resize function
• What is grades.length?
• How about grades[0].length?
(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html )
Example: array operations
System.out.println("Original:");
System.out.println(Arrays.toString(numArray));
System.out.println("Sorted:");
Arrays.sort(numArray);
System.out.println(Arrays.toString(numArray));
Example 2: array operations
int[] numArray = new int[100];
System.out.println("Original:");
System.out.println(Arrays.toString(numArray));
System.out.println("Sorted:");
Arrays.sort(numArray);
System.out.println(Arrays.toString(numArray));
if(result > 0) {
System.out.println("Found! Index:"+result);
} else {
System.out.println("Not found! Index:"+result);
}
Overview of today’s material
• Object-oriented programming:
- Composition
- inheritance
Wrappers
Wrappers
• By now, you should be familiar with the
distinction between primitive types and class
types
– Primitives: int, double, char
– Class (reference) types: everything else in Java
(e.g. String, Scanner, Circle, …)
double r = objectD.doubleValue();
Example for doubles:
double num = 5.0;
Double objectD = Double.valueOf(num);
double r = objectD.doubleValue();
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html
Auto-boxing/un-boxing
• Auto-boxing and auto-unboxing:
Integer wrapper_integer = 5; Integer wrapper_integer = Integer.valueof(5);
(Note: Java is smart-- don’t need to use valueOf method here to get Integer object)
The built-in Vector class will only store objects (not primitive types)
Overview of today’s material
• Object-oriented programming:
- Composition
- inheritance
More on object-oriented programming
Back to object-oriented programming: two important
concepts for today
• Composition:
Using classes as data members of other classes
– Generic Types
– Adapters
• Inheritance
Designing hierarchically organized classes that
“inherit” data members and methods
– Access to fields/methods of the base class
– Protected Access
– Overriding, Overloading Methods
Composition
A "has a"
relationship
fig 2-1
public Name () {
first = ""; last = "";
} // end default constructor
public Student () {
fullName = new Name (); id = ""; } // end default constructor
public Student () {
fullName = new Name (); id = ""; } // end default constructor
...
}
Two special cases of composition
• Generic types
– Class contains a member variable, but its type can
vary
– Example: we might have a data container that
could be used for multiple types, it would be nice
if we could pass the type as a “parameter”
• Adapters
– Using composition to customize an existing class–
remove/add methods or modify the names of
some of its existing methods
Generic Types
• Consider a class with fields that can be of any class type
• Use a generic type
– Follow class name with an identifier enclosed in angle
brackets
public class MyClass <T>
• T is a placeholder for the type, which you specify
when you instantiate an object from this class
• Rule: T can only be specified as a reference (class
type), doesn’t work with primitives
In a main method:
Point<Integer> start = new Point<Integer>(5, 7);
Point<Double> end = new Point<Double>(0.5,0.7);
Generics examples
start.setPoint(0.5,0.5);
end.setPoint(0.5,0.5);
start.setPoint(0.5,0.5);
end.setPoint(0.5,0.5);
} // end OrderedPair
In a main method:
OrderedPair<String> fruit = new OrderedPair<String>();
fruit.setPair("apples", "oranges"); Output:
System.out.println(fruit); (apples, oranges)
fruit.changeOrder(); (oranges, apples)
System.out.println(fruit);
A Generic type with multiple types
public NickName () {
nick = new Name ();
} // end default constructor
• Object-oriented programming:
- Composition
- Inheritance
Inheritance
Basic idea: objects are sometimes hierarchically related to
each other (abstractly) in that they “inherit” data or
methods from more general classes
public class
public UndergradStudent
Student () { {
private Name
fullName = fullName;
new Name (); id = ""; } // end default constructor
private String id; // identification number
public Student (Name studentName, String studentId) {
public
public Student
fullName
class () {
=HighSchoolStudent
studentName; id ={ studentId; } // end constructor
fullName
private = new
Name Name (); id = ""; } // end default constructo
fullName;
public void setStudent (Name id;
private String studentName, String studentId)
// identification number {
public Student
setName (Name studentName,
(studentName); String =studentId)
// or fullName {
studentName;
fullName
setIdpublic = studentName;
(studentId);
Student //
()or id = studentId; } // end constructor
{ id = studentId;
} // end setStudent fullName = new Name (); id = ""; } // end default con
public void setStudent (Name studentName, String studentId) {
setName
public void setName
public (studentName);
(Name studentName)
Student //
{ or fullName
(Name studentName, String= studentId)
studentName;
{
setId (studentId);
fullName = studentName; // or id
fullName = }studentName;= studentId;
// end setName
id = studentId; } // end con
} // end setStudent
public Name getName
public () { return
void fullName;
setStudent (Name }studentName, String studentId) {
public void setName (Name
setName studentName) //
(studentName); { or fullName = studentName;
public void setIdfullName
(String= studentId)
studentName;
setId { } //
(studentId); // end setName
or id = studentId;
id = studentId; } // end setId
} // end setStudent
public Name getName () { return fullName; }
public String public
getId () { setName (Name studentName) {
void
public void
return id;setId
} // (String = studentId)
end getId
fullName studentName;{ } // end setName
} id = studentId; } // end setId
public Name getName () { return fullName; }
public String getId () {
A better solution
• Use inheritance!
• Let’s define a general base (ancestor) class, Student, which
contains all the basic data/methods associated with any type
of student
• Then we can define several derived classes (descendants) that
inherit and extend the functionality of Student
The CollegeStudent derived class
public class CollegeStudent extends Student {
private int year; // year of graduation
private String degree; // degree sought
public CollegeStudent()
{
super();
year = 0;
degree = "";
} // end default constructor
year = graduationYear;
degree = degreeSought;
} // end setStudent
// < The methods setYear, getYear, setDegree, to String, and getDegree go here.>
// . . .
} // end CollegeStudent
Reminder: the Student class
public class Student {
private Name fullName;
private String id; // identification number
public Student () {
fullName = new Name (); id = ""; } // end default constructor
year = graduationYear;
degree = degreeSought;
} // end setStudent
For the boxed section, can we do this instead? Why or why not?
fullName = studentName;
id = studentId;
(default- no
modifier)
Is equivalent to:
Good practice: always be
explicitstudentId,
public CollegeStudent(Name studentName, String about which base
int graduationYear, String you
class constructor degreeSought)
want
{ to call
super();
year = graduationYear;
degree = degreeSought;
} // end constructor
In CollegeStudent class:
Note: you cannot override a private method from the base class
In CollegeStudent class:
public void setStudent(Name studentName, String studentId,
int graduationYear, String degreeSought)
{
setName(studentName);
setId(studentId);
// or setStudent(studentName, studentId);
year = graduationYear;
degree = degreeSought;
} // end setStudent
Example question
In Student class:
public void setStudent(Name studentName, String studentId)
{
setName(studentName); // or fullName = studentName;
setId(studentId); // or id = studentId;
} // end setStudent
In CollegeStudent class:
public void setStudent(Name studentName, String studentId)
{
setName(studentName);
setId(studentId);
// or setStudent(studentName, studentId);
year = 2022;
degree = “Not declared”;
} // end setStudent
Overriding or overloading?
Example question
public class Student
{
private Name fullName;
private String id; // identification number
public Student()
{
fullName = new Name();
id = "";
} // end default constructor
Overriding or overloading?
Inheritance: summary
public Student () {
fullName = new Name (); id = ""; } // end default constructor
• Note
– Comments of method purpose, parameters, pre-
and post-conditions
– Any data fields should be public, final, and static
– Interface methods cannot be final
or …
A class that implements this interface could begin with the statement
}
Comparable interface example
public class Circle implements Comparable < Circle > {
private double radius, xPos, yPos;
Color circColor;
Arrays.sort(circleArray);