Download presentation
Presentation is loading. Please wait.
Published byMarilynn Todd Modified over 6 years ago
1
Lecture 12 C Structs .jar files Intro to Classes and Objects
John Hurley
2
C Structs Consider this SQL query on a database table of monster attacks, and the data returned: MariaDB [monster_attacks]> SELECT * FROM attacks; | id | monster_name | attack_date | location | | 11 | Godzilla | | Tokyo | | 14 | Bigfoot | | Seattle | Each line represents a record with data on one monster attack. The data for each attack includes an int, two strings (varchars in SQL), and a date. 2
3
C Structs C has a data structure called a struct which is designed to hold a data record, which may include multiple data fields of various data types. C++ is a superset of C, and accordingly, it still has structs. Java, however, does not. You will see next week why Java's designers considered the struct unnecessary in Object Oriented Programming. However, it is easier to understand OOP if you first learn a little about structs. Structs include data but not functions. C functions may create structs, take them as parameters, and return them. The code on the next page contains several things that are "not the way you would really do it in C." It's intended to illustrate structs, not to teach C. The struct definition in the example includes three important data fields about a student. One instance of the struct represents data about one student. 3
4
C Structs #include <stdio.h> #include <stdlib.h>
#include <time.h> struct student{ int id; int age; float balance_owed; }; double get_total(struct student students[], int length){ float total= 0; for(int i = 0; i < length; i++) { double owed = students[i].balance_owed; total += owed; printf("Student %d is %d years old and owes $%8.2f\n", i, students[i].age, owed); } return total; int main(int argc, char **argv) { srand(time(NULL)); const int num_students = 10; struct student students[num_students]; for(int i = 0; i < num_students; i++) { students[i].id = i+1; students[i].age = (double)rand() / RAND_MAX * ; students[i].balance_owed = (double)rand() / RAND_MAX * 3000; printf("Total Amount Collectible= %.2f\n", get_total(students, num_students)); return 0; 4
5
Abstraction Some definitions of Abstract (adjective):
Considered apart from any application to a particular object; removed from; apart from; separate; abstracted. Apart from practice or reality; not concrete; ideal; vague; theoretical; impersonal. (art) Free from representational qualities. (logic) General (as opposed to particular). Synonyms (not applied or practical): conceptual, theoretical (insufficiently factual): formal - Source: Wiktionary In programming, abstraction is a fundamental concept that you need to think about in every program you write, like expense Programmers sometimes use the word “abstract” as a transitive verb meaning “to create an abstraction of,” as well as using the more common English usage of “abstract” as an adjective. 5
6
Abstraction Abstraction can be multi-layered:
A manhole cover is a round thing that covers a manhole to prevent people falling in and rats crawling out A round thing is a physical object that has the quality of being round Round means “in the shape of a circle” A circle is a geometric shape defined by a set of points which are equidistant from the center 6
7
Object Oriented Programming
The coding we have done so far is procedural programming, based mostly on writing instructions that describe how the computer can do things OOP is built on the foundation of procedural programming Object Oriented Programming is the current state of the art in creating modular code OOP is all about finding the right abstractions to use in our applications OOP is the main focus of this course 7
8
Classes And Objects Objects contain data and methods that are designed to work on the data In programming, an instance means a specific case. In Java, objects are instances of classes. We create them by instantiating classes. You have already done this with code like this: Scanner sc = new Scanner(); A class defines the data types and methods for objects, while an object contains actual data Think about the relationship between the definition of "table" and some actual table. The actual table has many specific characteristics that are not shared by tables in general or inherent in the idea of a table (Plato!) 8
9
Classes And Objects Most, but not all, classes are intended to serve as templates for objects In java and most (not all) other OO languages, an application is defined by one or more classes. In Java, classes are usually, but not always, defined in separate files, one file per class. “Inner classes” can be defined in the same file with the parent class. 9
10
Classes And Objects "Model" used as a verb in programming means to represent or imitate some of the characteristics and behaviors of something. Classes often model entities or abstractions that already exist outside the program String defines the data that must be present in any particular string of characters, such as "John", as well as numerous methods that manipulate the data A Ship class might have data variables including weight, country of registration, and engine displacement procedures (methods/ functions/ subroutines) including accelerate, show speed, drop anchor, fire cannon, hoist flag, scuttle A Rectangle class might have three data variables that represent coordinates methods to calculate area and perimeter and to determine whether a given coordinate is inside the rectangle 10
11
Classes And Objects Objects may have values for the variables defined in the class. Multiple objects of the same class have the same variables, but the actual data (the value of the variables) may be different every ship has a weight, but it may be different from the weight of any other ship in the world. running the same methods for different objects of the same class may produce different results since the methods operate on data values that may be different the behavior of one object may affect other objects of the same or other classes The first object-oriented programs modeled the behavior of ships in a harbor 11
12
Constructors Constructor method headers look like this:
public ClassName(parameters){} By convention, if programmer-defined constructors are present, they are the first methods listed in a class. A class may have more than one constructor (“constructor overloading”) as long as they take different arguments If you write one or more constructors, the compiler does not supply an implicit constructor. If you want one, you must write it yourself, which is very easy: public ClassName(){} For example, public Student(){} 13
13
Creating an object An object can be created using a no-parameter constructor like this: access modifier classname objectname = new classname(); For example, private Student mary = new Student(); Note that Student is the name of a class mary is a variable whose value is a reference to the object we created. The value of the variable mary is the address of the memory location where the data for the object starts The data type of the variable mary is Student private means that the variable mary is only visible from this object. 14
14
Creating an object An object can be created using a constructor that does take parameters like this: access modifier classname objectname = new classname(parameters); For example, if Student has a constructor that takes a String parameter, you can construct a Student by calling the constructor and sending the correct type of argument: private Student mary = new Student("Mary"); 15
15
Driver class Your classes that model real world entities or logical parts of your application should not contain test data, since that makes them useless with any other data. In most cases, they should not contain main() methods. A driver is a class that is intended to be used to test or demonstrate the functionality of other classes. It contains a main() that creates instances of other classes and runs their public methods. For example, if we are developing a Book class, we might write a driver that instantiates some Books, gives them ISBNs, titles, etc., and runs whatever public methods they have. We will learn a better way to do this in a few weeks. 17
16
Constructors 18 package lect4; public class Course {
private int courseNum; private String instructorName; public Course(int courseNumIn, String instructorNameIn){ courseNum = courseNumIn; instructorName = instructorNameIn; } public int getCourseNum() { return courseNum; public void setCourseNum(int courseNum) { this.courseNum = courseNum; public String getInstructorName() { return instructorName; public void setInstructorName(String instructorName) { this.instructorName = instructorName; public String toString(){ return courseNum + "; Instructor: " + instructorName; 18
17
Constructors private List<Course> courses;
package lect4; import java.util.ArrayList; import java.util.List; public class Department { private String deptName; private List<Course> courses; public Department(String deptNameIn) { courses = new ArrayList<Course>(); deptName = deptNameIn; } public String getDeptName() { return deptName; public void setDeptName(String deptNameIn) { this.deptName = deptNameIn; public List<Course> getCourses() { return courses; public void addCourse(Course course) { courses.add(course); public void dropCourse(Course course) { courses.remove(course); public String toString() { 19
18
Constructors 20 package lect4; import java.util.ArrayList;
import java.util.List; import javax.swing.JOptionPane; public class College { private List<Department> departments = new ArrayList<Department>(); public void administer() { String[] choices = { "Quit", "List Courses For A Department", "Add A Course", "Add A Department" }; int choice; do { choice = JOptionPane.showOptionDialog(null, "Main Menu", "Main Menu", 0, JOptionPane.QUESTION_MESSAGE, null, choices, "null"); switch (choice) { case 0: break; case 1: if (!(departments.isEmpty())) listDeptClasses(); case 2: addCourse(); case 3: addDept(); } // end switch } while (choice != 0); // end do }// end main 20
19
Constructors 21 private Department getDeptNameFromInput() {
int choice = JOptionPane.showOptionDialog(null, "Choose A Department", "Choose A Department", 0, JOptionPane.QUESTION_MESSAGE, null, departments.toArray(), "null"); // the choices must be an array return departments.get(choice); } private void listDeptClasses() { Department dept = getDeptNameFromInput(); if (departments.contains(dept)) { List<Course> deptCourses = dept.getCourses(); StringBuilder sb = new StringBuilder(dept.getDeptName() + " offers the following courses:\n "); if (deptCourses.isEmpty()) sb.append("None"); else for (Course c : deptCourses) sb.append(c + "\n"); // note that this will use the // toString() method of Course JOptionPane.showMessageDialog(null, sb); } // end if private void addCourse() { int courseNum = Integer.parseInt(JOptionPane .showInputDialog("Please enter the course number")); String instructorName = JOptionPane .showInputDialog("Please enter the name of the instructor in the new course"); dept.addCourse(new Course(courseNum, instructorName)); }// end if private void addDept() { String deptName = JOptionPane .showInputDialog("Please enter the name of the new department"); departments.add(new Department(deptName)); 21
20
Constructors 22 package lect4; public class Driver {
public static void main(String[] args) { College uSaskMooseJaw = new College(); uSaskMooseJaw.administer(); } 22
21
A Place To Stand This hard-to-understand idiom is commonly used in OOP examples. Be sure you see what is going on. The main() method creates an object *of the same class where it appears* and then uses its methods. Since main() is static, we don't need an instance of Archimedes to run it. We do, though, need an instance (an object of class Archimedes) to run sayHi(). public class Archimedes{ public static void main(String[] args){ Archimedes arch = new Archimedes(); arch.sayHi(); } private void sayHi(){ System.out.println("Hi!"); 23
22
Static Data Static data fields are controlled by the class, not the object. A static field has only one value for all instances of a class at any point during runtime
23
Static vs Instance Methods
Static methods like main() can be run using the class code without instantiating an object. JOptionPane.showMessageDialog(null, "hey"); Instance (non-static) methods can be run only as methods of particular objects instantiated from the class: Scanner sc = new Scanner(); double d = sc.nextDouble(); 25
24
Static Methods and Data
package demos; public class Borg { private String name; private static int borgCount; public Borg(String nameIn) { name = nameIn; borgCount += 1; } public void stateName() { System.out.println(name + " of " + borgCount); public static void main(String[] args) { int max = 9; borgCount = 0; Borg[] borgs = new Borg[max]; for (int counter = 0; counter < max; counter++) { String name = String.valueOf(counter + 1); borgs[counter] = new Borg(name); borgs[counter].stateName();
25
Why don’t we just use static methods for everything?
public class Clone{ private String name; public Clone(String nameIn){ name = nameIn; } public static void main(String[] args){ Clone bob = new Clone("Bob"); Clone joe = new Clone("Joe"); Clone mary = new Clone("Mary"); bob.greet(); joe.greet(); mary.greet(); private void greet(){ System.out.println("Hi, my name is " + name); This example uses three instances of the same class, which each have different data. We can run the same method from each object, getting different results for each one. 27
26
Use static methods and data sparingly
OOP allows us to model entitities (nouns, like Dog, Ship, Student, etc) with multiple objects that have the same type but contain different data (eg, many Students with different names.) Since static data is stored with the class, it is the same for every object of the same type. Static methods can't use instance data. The most obvious reason for this is that there may not be an instance. Therefore, using static methods and data loses some of the benefits of OOP, which is what this course is all about Only use static methods (other than main()) and data if there is a clear reason, like counting the number of instances of a class. I will mark your work down if you use static methods where instance methods make more sense. 28
27
main() As you know, the JVM executes the application by invoking (running) the main() method, which may then call other methods So far, all your classes have contained main() methods We will soon begin writing programs that contain more than one class. In your CS202 programs, only one class per program will need a main(). The example used for constructors above contained three classes, of which one contained a main(). Here is another example. 29
28
Multi-class application
This class will be used as a data type in an application. Notice that there is no main() method. This class has only the implicit constructor, so the data fields initially have default values (0.0 for the double) name and grade are called “instance variables” because there is one name and one grade for each object of the class Student, that is, for each instance of Student. package demos; public class Student { private String name; private double grade; public String getName() { return name; } public double getGrade() { return grade; public void setName(String nameIn) { name = nameIn; public void setGrade(double gradeIn) { grade = gradeIn; 30
29
Multi-class application
/* GradeBook and Student are in the same package. If they were in different packages, we would need an import */ package demos; public class GradeBook { public static void main(String[] args) { // create an array of Students Student[] students = new Student[4]; // create Students and put them in the array for(int counter = 0; counter < students.length; counter++) students[counter] = new Student(); // supply data for the Students students[0].setName("Fred"); students[0].setGrade(82.0); students[1].setName("Wilma"); students[1].setGrade(86.5); students[2].setName("Barney"); students[2].setGrade(63.0); students[3].setName("Betty"); students[3].setGrade(96.5); // output the data for(Student s: students) System.out.println(s.getName() + ": " + s.getGrade()); } 31
30
Compiling Multi-Class Apps
Note that, when you compile the first class in an app from the command line, it will compile all classes it can find in a chain of references If class a refers to class b, but b does not have a reference to a, it is easier for you to compile a first. If you compile using an IDE, you don't have to worry about this. 32
31
Definition: State State is the configuration of data at one point in time An object’s state is the set of values of its data fields at one instant
32
Public and Private As your programs get more complex, you will lose track of the details of the parts you are not currently working on In your advanced programming classes, you will collaborate with other programmers who may not solve problems in the same way you would Professional software applications may contain code written by hundreds or even thousands of programmers working for many different employers. More than 10,000 programmers have worked on the Linux kernel. All software contains errors, and some also contains intentionally malicious code. 34
33
Public and Private Public data may be accessed directly by any object that has a reference to the current object This means that any other object can change your data in any way that seems appropriate to whoever wrote it This leads to unpredictable behavior, because programmers are almost as crazy as users Private fields and methods may only be used from within the current object Most classes have private data which can be accessed or changed only by using public methods The public methods are part of the object and thus can see or change the private data 35
34
Public and Private We can reduce the confusion by providing well-defined interfaces instead of allowing other objects to access our data directly To use an object of a certain class, you only need to know its public methods. You can protect the data in your own classes by allowing it to be changed or accessed only by methods you wrote and chose to make publicly available This principle is called information hiding or encapsulation 36
35
Public and Private The sport of American football includes several ways to score points. The main ones are these: A touchdown scores 6 points A conversion, also called an extra point, scores one point but can only be scored immediately after a touchdown A safety scores 2 points A field goal scores 3 points Note that there is no way to score four, five, seven, etc. points at once 37
36
Public and Private public class FootballScore {
// models the score for one team in a game of American Football private int score; public int getScore() { return score; } public void touchdown() { score += 6; public void extraPoint() { score += 1; public void safety() { score += 2; public void fieldGoal() { score += 3; 38
37
Public and Private How the private data / public methods architecture benefits FootballScore: If external objects (say, a FootballGame object) could arbitrarily change the score in FootballScore, buggy or malicious code could interfere with the functioning of the class for example, by adding 5 to the score or dividing it by 2, changes that are invalid in American Football. this kind of problem is hard to find and extremely hard to fix, since the bad code was probably written by someone else In FootballScore, the available ways to change the score are limited to the ways points can actually be scored in Football If anything else needs to be done when the score changes, like updateScoreboard(); or notifyBookmaker(); the author of FootballScore can take responsibility for making sure the public methods trigger it 39
38
Public and Private How the private data / public methods architecture benefits objects that use FootballScore: Other objects do not have to understand the internal functioning of FootballScore They only need to know that they can find out the score by calling getScore() and can deal with scoring events by calling, for example, touchdown(). If you decide to change the design of FootballScore, nothing in any other class needs to change as long as the public interface remains the same. This will become very important as your classes get more sophisticated. Suppose you write a class with a method that determines whether or not a touchdown was actually scored. You may sometimes need to change the algorithm used by the method (eg, to use new electronic sensors or to accommodate rule changes in the sport.) As long as the method signature remains the same, other objects don't need to understand anything about it or even know when you change it. 40
39
Package Private The default visibility is package private
Package private data and methods are visible to any object of a class defined in the package This is rarely what you actually want 41
40
Accessors and Mutators
Methods like getScore() are called “Accessors” because they provide access to the data. These are informally called “getters.” Methods like touchdown() are called “Mutators” because they change data. These are also informally called “setters.” It's conventional to provide and use getters and setters even when the data is public 43
41
This The keyword this is a reference to the current object.
It has many uses; one is for the case that a setter has a parameter with the same name as the field in the class. private int heightInCm; public void setHeightInCm(int heightInCm){ this.heightInCm = heightInCm; } You need to understand this usage, but you don't have to like it. You can just use a different name for the parameter in the method signature: public void setHeightInCm(int heightInCmIn){ heightInCm = heightInCmIn; 44
42
toString() Consider this code (Student must also be in the package or be imported): public class Demo { public static void main(String args[]) { Student joe = new Student(); joe.setName("Joe"); joe.setGrade(100.0); System.out.println(joe); } // end main() } The output will look approximately like this: We have not printed out the useful information in the object, just the name of the class and the hash code (a value used internally by the compiler and JVM for various purposes) of the object! 45
43
toString() There is a built-in toString() method that shows the name of the class and the hash code of the object. This is what we got in the last example. If you want to provide a more useful String representation of objects, write a toString() method in the class. toString() is public, takes no parameters, and returns a String, so its method header is public String toString() We might add a toString() like this to Student: public String toString(){ return "Name: " + name + "; Grade: " + grade; } If we now run the same code from Gradebook, we get this output: Name: Joe; Grade: 100.0 46
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.