Download presentation
Presentation is loading. Please wait.
Published byMarja-Leena Niemelä Modified over 5 years ago
1
Lecture 2 Introduction to Classes and Objects
2
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. 2 2
3
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 3 3
4
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 4
5
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 5
6
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 actual table has many specific characteristics that are not shared by tables in general or inherent in the idea of a table 6 6
7
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 class. An inner class can be defined in the same file with the parent class. 7 7
8
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 8
9
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 9
10
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 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 10 10
11
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 11
12
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 12
13
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 very easy: public ClassName(){} For example, public Student(){} 13 13
14
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 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 and objects of the same class (this will get a little more complicated soon.) 14 14
15
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 constructor and sending the correct type of argument: private Student mary = new Student("Mary"); 15 15
16
Calling methods on another 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. Student fred = new Student(); fred.setGrade(80.5); 16 16
17
Constructors 17 17 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 17
18
Constructors 18 18 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() { 18 18
19
Constructors 19 19 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 } 19 19
20
Constructors 20 20 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)); 20 20
21
Constructors 21 21 package lect4; public class Driver {
public static void main(String[] args) { College uSaskMooseJaw = new College(); uSaskMooseJaw.administer(); } 21 21
22
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 22
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(); 23 23
24
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
25
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
26
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){ name = nameIn; private void sayHi() { System.out.println("Hi, I'm " + name); 26 26
27
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 27
28
Use static methods and data 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 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 28
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.