csns.calstatela.edu

csns.calstatela.edu

Lecture 2 Introduction to Classes and Objects 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

2 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 3 which are equidistant from the center 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 4 Classes And Objects The term "object" is short for "object in memory," i.e. a unit of data that can be found at some memory address "Object" as used in Object-Oriented Programming refers to a more specific type of object.

5 Classes And Objects In OOP, an instance means a specific case. In Java and most (not all) other OOP languages, objects are instances of classes. We create them by instantiating classes. You have already done this with code like this: Scanner sc = new Scanner(System.in); 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

6 Classes And Objects Most, but not all, OOP classes are intended to serve as templates for objects In Java and most (not all) other OO languages, an application is defined by (consists of) one or more classes. In Java, classes are usually, but not always, defined in separate files, one file per 7 class. An inner class can be defined in the 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 8 Classes And Objects 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 9 Classes And Objects An Object (an instance of a class) 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 10 may be different the behavior of one object may affect other Constructors Constructors are methods that create objects, using the class as a template. Constructors may set values for data fields or do other initialization Every class has at least one constructor 11 Constructors In Java, if you do not write any

constructors, the compiler provides an implicit constructor, which is not shown in the code. Implicit constructors take no parameters and do not set any data values or run any other methods 12 Constructors Constructor 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) if they take different

argument types 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 13 very easy: 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 the name of a variable whose value is a reference 14 object we to the created. The value of the variable mary is the address of the memory location where the data for the 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, Student might have a constructor that takes a String parameter used to set the name of the student. If so, you can construct an object of class Students (an instance of Student) by calling the

15 constructor and sending the correct type of argument: object If we have a variable that refers to an object, we can call public methods on the object like this: variablename.methodname(parameters) Example: The Student class contains a method called setGrade(), which takes one double as an argument. fred will be a variable of type Student. 16 Constructors

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; 17 Constructors package lect4; import java.util.ArrayList; import java.util.List; public class Department { private String deptName; private List courses;

public Department(String deptNameIn) { courses = new ArrayList(); deptName = deptNameIn; } public String getDeptName() { return deptName; } public void setDeptName(String deptNameIn) { this.deptName = deptNameIn; } public List getCourses() { return courses; } public void addCourse(Course course) { courses.add(course);

18 Constructors package lect4; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class College { private List departments = new ArrayList(); 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(); break; case 2: if (!(departments.isEmpty())) addCourse(); break; 19

Constructors 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 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() { Department dept = getDeptNameFromInput(); if (departments.contains(dept)) { 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");

20 package lect4; Constructors public class Driver { public static void main(String[] args) { College uSaskMooseJaw = new College(); uSaskMooseJaw.administer(); } } 21 Definition: State

State is the configuration of data at one point in time An objects state is the set of values of its data fields at one instant 22 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(); 23 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 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); } 25 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 in which it appears* and then makes method calls on the object. Since main() is static (not part of a particular object), 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 { private String name;

public static void main(String[] args) { Archimedes arch = new Archimedes("Archie"); Archimedes betty = new Archimedes("Betty"); arch.sayHi(); betty.sayHi(); } public Archimedes (String nameIn){ 26 Why dont 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); 27

sparingly OOP allows us to model entities (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 28 use static methods (other than main()) and data if there is a Only clear reason, like counting the number of instances of a class.

Recently Viewed Presentations

  • Plant Defense Responses - Strongsville City Schools

    Plant Defense Responses - Strongsville City Schools

    Plant Defense Responses Elisa Russo & Ben Strozyk 2011 The Attack on Plants Viruses, bacteria, fungi, animals, and other plants can attack They attack by spore germination, hyphae growing through cell walls, and hyphae differentiating into specialize haustoria Responses by...
  • Planning the Instruction - MSU Billings

    Planning the Instruction - MSU Billings

    Planning the Instruction. Last week we covered the importance of designing a curriculum based on national, state, and local standards. We learned the difference between goals and objectives and that we need to include multiple hierarchies (cognitive, affective, and psychomotor...
  • 7 - Dr. Jerry Cronin

    7 - Dr. Jerry Cronin

    Mental. foramen (a) Anterior view. Mandibular symphysis. Frontal bone. Glabella. Frontonasal suture. Supraorbital foramen (notch) ... fossa. Temporal bone (petrous part) Posterior. cranial fossa. Parietal bone. Occipital bone. Foramen magnum (a) Superior view of the skull, calvaria removed.
  • Devices of Satire - Woodland Hills School District

    Devices of Satire - Woodland Hills School District

    Exaggeration by saying more than you mean to say—all hyperbole is a form of overstatement Overstatement in William Shakespeare's Macbeth: In Shakespeare's tragedy Macbeth, in order to gain the crown, Macbeth and his wife, Lady Macbeth, have plotted to successfully...
  • The &quot;New&quot; Competitive Bidding: Proposed Rule and Other ...

    The "New" Competitive Bidding: Proposed Rule and Other ...

    Bidding suppliers that provide a falsified bid bond will be prohibited from participation in the competitive bid program for the current and next round of bidding. Bidding suppliers that provide a falsified bid surety bond will also be referred to...
  • 1 Introduction to the Programme  Michael 2 Maths

    1 Introduction to the Programme Michael 2 Maths

    Martin Greenhow (Brunel) Janet Strivens (Liverpool) Jane White (Bath) Tony Croft (Loughborough) Duncan Lawson (Coventry) CETL-MSOR Conference. Annual conference will continue for 2011 and 2012. 5th & 6th September 2011 at Coventry University.
  • Airway Management PRESENTED BY : DR.ABBASI Endotracheal Intubation

    Airway Management PRESENTED BY : DR.ABBASI Endotracheal Intubation

    وقتی که لازم باشد تهویه برای مدت طولانی با فشار مثبت(ppv) انجام شود چه با آمبوبگ چه با ونتیلاتور. زمانی که تهویه با بگ و ماسک بی اثر باشد.
  • Reconstruction: 1865-1877 - Loudoun County Public Schools

    Reconstruction: 1865-1877 - Loudoun County Public Schools

    The sharecropper rents a piece of land from the landowner. This rent includes a shack, seeds and farming tools. The sharecropper promises to give the landowner a percentage of the crops. The sharecropper plants and harvest the crops such as...