Download presentation
Presentation is loading. Please wait.
Published byTrevor Wilcox Modified over 9 years ago
1
1 Object-Oriented Programming James Atlas June 12, 2008
2
James Atlas - CISC3702 Questions? Review… Review… Java is …?
3
June 12, 2008James Atlas - CISC3703 Java Editions Different Java Editions Different Java Editions SE: Standard Edition EE: Enterprise Edition Server-side applications Server-side applications Web applications, Communication (mail) Web applications, Communication (mail) ME: Micro Edition For PDAs, mobile devices, etc. For PDAs, mobile devices, etc.
4
June 12, 2008James Atlas - CISC3704 Your Surveys Web application programming Web application programming This class: briefly on client-side (Applets) and server- side programming (Servlets, JSPs) Good starting point to learn more on your own CISC474: Advanced Web Technologies Web Application Server Browser (Client) Servlets, JSPs Applet
5
June 12, 2008James Atlas - CISC3705 Course Topics Java Fundamentals Java Fundamentals APIs APIs GUIs Threads XML Network programming RMI Web applications: Servlets, JSPs
6
June 12, 2008James Atlas - CISC3706 A Little More Arrays Arrays is a class in java.util Arrays is a class in java.util Methods for sorting, searching, “deepEquals”, fill arrays Methods for sorting, searching, “deepEquals”, fill arrays Wouldn’t these methods have been useful in 105 or 181?
7
June 12, 2008James Atlas - CISC3707 Eclipse Everyone has it setup? Everyone has it setup? Open project, find source code for Java SDK Open project, find source code for Java SDK Let’s look at the java.util.Arrays class Let’s look at the java.util.Arrays class
8
June 12, 2008James Atlas - CISC3708 Today Object-Oriented Programming Object-Oriented Programming Objects Classes Instances Encapsulation Methods Inheritance Abstraction Polymorphism
9
June 12, 2008James Atlas - CISC3709 Object-Oriented Programming Programming that models real life Programming that models real life Consider an ATM… Implicitly agreed upon interface between user and the calculator Implicitly agreed upon interface between user and the calculator What, not how What, not how Objects each have own role/responsibility As opposed to functional programming As opposed to functional programming A list of instructions to the computer
10
June 12, 2008James Atlas - CISC37010 Objects How object does something doesn’t matter How object does something doesn’t matter What object does matters (its functionality) What object does matters (its functionality) What object exposes to other objects Referred to as “black-box programming” Object Has public interface that others can use Hides state from others
11
June 12, 2008James Atlas - CISC37011 Objects: Black-box programming If an object allows you to access and store data, you don’t care if the underlying data type is an array or hashtable, etc. If an object allows you to access and store data, you don’t care if the underlying data type is an array or hashtable, etc. It just has to work! And, you don’t need to implement a new object to do the job. Similarly, if object sorts, does not matter if uses merge or quick sort Similarly, if object sorts, does not matter if uses merge or quick sort
12
June 12, 2008James Atlas - CISC37012 Classes & Objects Classes define template from which objects are made Classes define template from which objects are made “cookie cutters” - Define state - data, usually private Define behavior - methods for an object, usually public
13
June 12, 2008James Atlas - CISC37013 Java Objects Java is pure object-oriented programming Java is pure object-oriented programming all data and methods in a program must be contained within an object/class all classes are actually objects - instances of java.lang.Class Example: java.lang.Object Example: java.lang.Object
14
June 12, 2008James Atlas - CISC37014 Instances Many objects can be created for a class Object: the cookie! Object, a.k.a. an instance of the class
15
June 12, 2008James Atlas - CISC37015 Instances Example Example: Chicken class Example: Chicken class State State Weight, height, name Chicken Fred: 2.0lb,38cmSallie Mae: 3.0lb,45cm Momma: 6.0lb,83cm
16
June 12, 2008James Atlas - CISC37016 Encapsulation Terminology is the combining of data and behavior (functionality) into one package (the object) and hiding the implementation of the data from the user of the object. Encapsulation is the combining of data and behavior (functionality) into one package (the object) and hiding the implementation of the data from the user of the object. the object’s data/variables instance fields: the object’s data/variables methods: the functions & procedures which operate on the object’s data methods: the functions & procedures which operate on the object’s data
17
June 12, 2008James Atlas - CISC37017 Example: Chicken class State State Weight, height, name Behavior Behavior Accessor methods getWeight, getHeight, getName getWeight, getHeight, getName Convention: “get” for “getter” methods Convention: “get” for “getter” methods Mutator methods eat: adds weight eat: adds weight sick: lose weight sick: lose weight changeName changeName
18
June 12, 2008James Atlas - CISC37018 Exercise: Designing the Pizza Class State State Behavior Behavior
19
June 12, 2008James Atlas - CISC37019 Constructors Constructor: a special method which constructs and initializes an object Constructor: a special method which constructs and initializes an object After construction, you can call methods on an object Constructors have the same name as their classes Constructors have the same name as their classes To create an object of a certain type (a certain class), use the new operator, much like in C++ To create an object of a certain type (a certain class), use the new operator, much like in C++
20
June 12, 2008James Atlas - CISC37020 Constructing objects using new Create three chickens Create three chickens “Fred”, weight: 2.0, height: 38 “Sallie Mae”, weight: 3.0, height: 45 “Momma”, weight: 6.0, height: 83 Chicken constructor Chicken constructor Chicken( String name, int height, double weight) Create new objects (Chickens) Create new objects (Chickens) Chicken one = new Chicken(“Fred”, 38, 2.0); Chicken two = new Chicken(“Sallie Mae”, 45, 3.0); And Momma? …
21
June 12, 2008James Atlas - CISC37021 Object References Variable of type object: value is memory location Variable of type object: value is memory location one = two = Chicken weight = height = name = 2.0 38 “Fred” Chicken weight = height = name = 3.0 45 “Sallie Mae”
22
June 12, 2008James Atlas - CISC37022 Object References Variable of type object: value is memory location Variable of type object: value is memory location one = two = If I haven’t called the constructor, only Chicken one; Chicken two; Both one and two are equal to null
23
June 12, 2008James Atlas - CISC37023 Null Object Variables An object variable can be explicitly set to null. An object variable can be explicitly set to null. indicates that this object variable does not currently refer to any object. It is possible to test if an object variable is set to null It is possible to test if an object variable is set to null Chicken chick = null; … … … if (chick == null) {... }
24
June 12, 2008James Atlas - CISC37024 Exercise: Designing the Pizza Class Constructors? Constructors?
25
June 12, 2008James Atlas - CISC37025 Relationship to C++ Java object variables similar to object pointers in C++ Java object variables similar to object pointers in C++ For example, For example, String myString; // Java is really the same as: String * my_string; // C++ Every object variable in Java is like a pointer to an object in C++ Every object variable in Java is like a pointer to an object in C++
26
June 12, 2008James Atlas - CISC37026 Multiple Object Variables more than one object variable can refer to the same object more than one object variable can refer to the same object Chicken weight = height = name = 3.0 45 “Sallie Mae” sal = sal2 = Chicken sal = new Chicken(“Sallie Mae”); Chicken sal2 = sal;
27
June 12, 2008James Atlas - CISC37027 What happens here? Chicken x, y; Chicken z = new Chicken(“baby”, 1.0, 5); x = new Chicken(“ed”, 10.3, 81); y = new Chicken(“mo”, 6.2, 63); Chicken temp = x; x = y; y = temp; z = x;
28
June 12, 2008James Atlas - CISC37028 Encapsulation Revisited Objects should hide their data and only allow other objects to access this data through accessor and mutator methods. Objects should hide their data and only allow other objects to access this data through accessor and mutator methods. Common programmer mistake: Common programmer mistake: creating an accessor method that returns a reference to a mutable (changeable) object.
29
June 12, 2008James Atlas - CISC37029 Immutable Objects: java.lang.String Immutable objects have only accessors Immutable objects have only accessors java.lang.String holds a char[] java.lang.String holds a char[] No method returns a reference to this char[] No method returns a reference to this char[]
30
June 12, 2008James Atlas - CISC37030 What is “bad” about this class? class Farm {... private Chicken headRooster; public Chicken getHeadRooster() { return headRooster; }... }
31
June 12, 2008James Atlas - CISC37031 Fixing the Problem: Cloning class Farm {... private Chicken headRooster; public Chicken getHeadRooster() { return (Chicken) headRooster.clone(); }... } Another Chicken object, with the same data as headRooster is created and returned to the user. If the user modifies (e.g., feeds) that object, it does not affect headRooster.
32
June 12, 2008James Atlas - CISC37032 Cloning Cloning is a more complicated topic than it seems from the example. Cloning is a more complicated topic than it seems from the example. We will examine cloning in more detail at a later point. We will examine cloning in more detail at a later point.
33
June 12, 2008James Atlas - CISC37033 Access Modifiers A public method (or instance field) means that any object of any class can directly access the method (or field) A public method (or instance field) means that any object of any class can directly access the method (or field) Least restrictive A private method (or instance field) means that any object of the same class can directly access this method (or field) A private method (or instance field) means that any object of the same class can directly access this method (or field) Most restrictive There are also other access modifiers, which will be discussed with Inheritance There are also other access modifiers, which will be discussed with Inheritance
34
June 12, 2008James Atlas - CISC37034 Method Parameters in C Call-by-value – a copy of the parameter is passed into the function/method. Call-by-value – a copy of the parameter is passed into the function/method. Call-by-reference – the memory location of the parameter is passed into the function/method. Call-by-reference – the memory location of the parameter is passed into the function/method.
35
June 12, 2008James Atlas - CISC37035 Method Parameters in Java Java always passes parameters into methods call-by-value. Java always passes parameters into methods call-by-value. methods cannot change the variables used as input parameters.
36
June 12, 2008James Atlas - CISC37036 What’s the output? int x; x = 27; System.out.println(x); doubleValue(x); System.out.println(x);... void doubleValue(int p) { p = p * 2; }
37
June 12, 2008James Atlas - CISC37037 What’s the output? Farm farm = new Farm(“OldMac”); Chicken sal = new Chicken(“Sallie Mae”, 50, 10); System.out.println(sal.getWeight()); farm.feedChicken(sal); System.out.println(sal.getWeight());... void feedChicken(Chicken c) { c.setWeight( c.getWeight() +.5); }
38
June 12, 2008James Atlas - CISC37038 What’s the difference? sal is an object variable, not an object sal is an object variable, not an object refers to an object (think of it as being a pointer to an object of the Chicken class). a copy of the object variable (the reference) is passed into the method. a copy of the object variable (the reference) is passed into the method. a copy of a reference refers to the same object! we can modify the state of an object in this manner
39
June 12, 2008James Atlas - CISC37039 Summary of Method Parameters Everything is passed call-by-value in Java. Everything is passed call-by-value in Java. An object variable (not an object) is passed into a method An object variable (not an object) is passed into a method changing the state of an object in a method changes the state of that object outside the method the method does not see a copy of the original object
40
June 12, 2008James Atlas - CISC37040 Varargs New in Java 1.5 New in Java 1.5 A method can take a variable number of arguments A method can take a variable number of arguments void varargsMethod(String... args) { for (int i=0;i < args.length; i++) System.out.println(“arg ”+ i + “ is “ + args[i]); } Why would you want to do this? Hint: Java now has a System.out.printf function
41
June 12, 2008James Atlas - CISC37041 Constructors
42
June 12, 2008James Atlas - CISC37042 Constructor Conventions A constructor is a special method that defines an object’s initial state A constructor is a special method that defines an object’s initial state Always has the same name as the class Always has the same name as the class A class can have more than one constructor A class can have more than one constructor A constructor can have zero, one, or multiple parameters A constructor can have zero, one, or multiple parameters A constructor has no return value A constructor has no return value A constructor is always called with the new operator. A constructor is always called with the new operator.
43
June 12, 2008James Atlas - CISC37043 Constructor Overloading Allowing more than one constructor (or any method with the same name) is called overloading. Allowing more than one constructor (or any method with the same name) is called overloading. each of the methods that have the same name must have different parameters Overload resolution is the process of matching a method call to the correct method by matching the parameters Overload resolution is the process of matching a method call to the correct method by matching the parameters handled by the compiler
44
June 12, 2008James Atlas - CISC37044 Default Initialization Unlike C and C++, if an instance field is not set explicitly in a constructor, it is automatically set to a default value Unlike C and C++, if an instance field is not set explicitly in a constructor, it is automatically set to a default value Numbers are set to zero Booleans are set to false Object variables are set to null It is a bad idea to rely on defaults It is a bad idea to rely on defaults Code is harder to understand Set all instance fields in the constructor(s).
45
June 12, 2008James Atlas - CISC37045 Default Constructor A default constructor is a constructor that has no parameters. A default constructor is a constructor that has no parameters. If no constructors are present in a class, a default constructor is provided by the compiler If no constructors are present in a class, a default constructor is provided by the compiler default sets all instance fields to their default values If a class supplies at least one constructor but no default constructor, the default constructor is NOT provided If a class supplies at least one constructor but no default constructor, the default constructor is NOT provided
46
June 12, 2008James Atlas - CISC37046 Default Constructor Chicken class has only one constructor: Chicken class has only one constructor: Chicken(String name, float weight, float height) So, there is no default constructor So, there is no default constructor Chicken chicken = new Chicken(); Is a syntax error Is a syntax error
47
June 12, 2008James Atlas - CISC37047 Explicit Field Initialization If more than one constructor needs to set a certain instance field to the same value, the initial state of the field can be set explicitly, in the field declaration If more than one constructor needs to set a certain instance field to the same value, the initial state of the field can be set explicitly, in the field declaration class Chicken { private String name = “”;... }
48
June 12, 2008James Atlas - CISC37048 Explicit Field Initialization Or in a static method call Or in a static method call class Employee { private int id = assignID();... private static int assignID() { int r = nextID; nextID++; return r; } More on static later…
49
June 12, 2008James Atlas - CISC37049 Explicit Field Initialization The ordering of explicit field initialization with relation to the constructor is important. The ordering of explicit field initialization with relation to the constructor is important. Explicit field initialization happens before any constructor runs. Explicit field initialization happens before any constructor runs. if one constructor wants to change an instance field that was set explicitly, it can. if one constructor wants to change an instance field that was set explicitly, it can. If the constructor does not set the field explicitly, explicit field initialization is used If the constructor does not set the field explicitly, explicit field initialization is used
50
June 12, 2008James Atlas - CISC37050 final keyword An instance field can be made final. An instance field can be made final. If an instance field is final, it must be set in the constructor or in the field declaration and cannot be changed after the object is constructed If an instance field is final, it must be set in the constructor or in the field declaration and cannot be changed after the object is constructed private final String type = Cards.HEARTS; private final String id; … public MyObject( String id ) { this.id = id; }
51
June 12, 2008James Atlas - CISC37051 Constructors calling constructors It is possible to call a constructor from inside another constructor. It is possible to call a constructor from inside another constructor. If the first statement of a constructor has the form If the first statement of a constructor has the form this(... ); the constructor calls another constructor of the same class. this keyword works just like in C++; an implicit parameter refers to the object being constructed
52
June 12, 2008James Atlas - CISC37052 Constructors calling constructors Why would you want to call another constructor? Why would you want to call another constructor? Reduce code size/reduce duplicate code
53
June 12, 2008James Atlas - CISC37053 Object Destructors In C++ (and many other OOP languages), classes have explicit destructor methods that run when an object is no longer used. In C++ (and many other OOP languages), classes have explicit destructor methods that run when an object is no longer used. Java does not support destructors, as it provides automatic garbage collection Java does not support destructors, as it provides automatic garbage collection Watches/waits until there are no references to an object Reclaims the memory allocated for the object that is no longer used
54
June 12, 2008James Atlas - CISC37054 finalize() Java supports a method named finalize(). Java supports a method named finalize(). method is called before the garbage collector sweeps away the object and reclaims the memory method is called before the garbage collector sweeps away the object and reclaims the memory This method should not be used for reclaiming any resources This method should not be used for reclaiming any resources the timing when this method is called is not deterministic or consistent only know it will run sometime before garbage collection
55
June 12, 2008James Atlas - CISC37055 Using finalize() What do we do in a finalize() method? What do we do in a finalize() method? We clean up anything that cannot be atomically cleaned up by the garbage collector We clean up anything that cannot be atomically cleaned up by the garbage collector Close file handles Close network connections Close database connections etc…
56
June 12, 2008James Atlas - CISC37056 Static Methods/Fields For related functionality/data that isn’t specific to any particular object For related functionality/data that isn’t specific to any particular object java.lang.Math java.lang.Math No constructor (what does that mean?) Static fields: PI, E Static methods: static double ceil(double a)
57
June 12, 2008James Atlas - CISC37057 Static Methods Do not operate on objects Do not operate on objects Cannot access instance fields of their class. Cannot access instance fields of their class. Can access static fields of their class. Can access static fields of their class.
58
June 12, 2008James Atlas - CISC37058 Static Fields A static field implies that there is only one such field per class (not object!). A static field implies that there is only one such field per class (not object!). All objects of a class with a static field share one copy of that field. All objects of a class with a static field share one copy of that field. For example, if we wanted to have a unique studentID for a Student class… For example, if we wanted to have a unique studentID for a Student class… class Student { private int id; private static int nextID = 1;... }
59
June 12, 2008James Atlas - CISC37059 Static Fields class Student { private int id; private static int nextID = 1;... } Each Student object has an id field, but there is only one nextID field, shared among all instances of the class Each Student object has an id field, but there is only one nextID field, shared among all instances of the class nextID field is present even when no Students have been constructed. How would we use the nextID field to create unique IDs?
60
June 12, 2008James Atlas - CISC37060 Final Static Fields We can also use a static field to make a constant in a class… We can also use a static field to make a constant in a class… The Math class has a static constant, PI The Math class has a static constant, PI The value can be accessed using the Math class: a = b * Math.PI; Notice we do not need to create an object of the Math class to use this constant. Notice we do not need to create an object of the Math class to use this constant. public class Math {... public static final double PI = 3.14..; }
61
June 12, 2008James Atlas - CISC37061 main() The most popular static method we have seen so far is the main() method. The most popular static method we have seen so far is the main() method. The main() method does not operate on any objects The main() method does not operate on any objects It runs when a program starts…there are no objects yet. main() executes and constructs the objects the program needs and will use. main() executes and constructs the objects the program needs and will use.
62
June 12, 2008James Atlas - CISC37062 Analyzing java.lang.String Look at Java Docs for Constructors String toUpperCase() Converts all of the characters in this String to upper case static String valueOf(boolean b) Returns the string representation of the boolean argument. What methods/fields should be static for the Pizza class?
63
June 12, 2008James Atlas - CISC37063 Static Summary Static fields and methods are part of a class and not an object Static fields and methods are part of a class and not an object do not require an object of their class to be created in order to use them. When would we use a static method? When would we use a static method? When a method does not have to access an object state (fields) because all needed data are passed into the method. When a method only needs to access static fields in the class
64
June 12, 2008James Atlas - CISC37064 (Returning) Explicit Field Initialization Or in a static method call Or in a static method call class Employee { private int id = assignID();... private static int assignID() { int r = nextID; nextID++; return r; }
65
June 12, 2008James Atlas - CISC37065 Class Design/Organization Fields Fields Chosen first Placed at the beginning or end of the class Has an accessor modifier, data type, variable name and some optional other modifiers If no accessor modifer --> package-private If no accessor modifer --> package-private Use this keyword to access the object Constructors Constructors Methods Methods Maybe public static void main
66
June 12, 2008James Atlas - CISC37066 Next Class More Object-Oriented Programming More Object-Oriented Programming Inheritance Abstraction Polymorphism
67
June 12, 2008James Atlas - CISC37067 Programming Assignment 1 Available in MyCourses Available in MyCourses www.cis.udel.edu/~atlas/cisc370/assignments/assign1.html www.cis.udel.edu/~atlas/cisc370/assignments/assign1.html
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.