classes, methods, & objects

Download Classes, Methods, & Objects

Post on 08-Feb-2016




0 download

Embed Size (px)


Classes, Methods, & Objects. Objectives. Review public and private fields and methods Learn the syntax for defining constructors and creating objects Learn the syntax for defining and calling methods - PowerPoint PPT Presentation



Classes, Methods, & ObjectsObjectivesReview public and private fields and methodsLearn the syntax for defining constructors and creating objectsLearn the syntax for defining and calling methodsLearn how parameters are passed to constructors and methods and how to return values from methods

Learn about static and instance fields and methodsLearn about method overloading.Learn about the copy constructor.Learn about encapsulation .

TerminologyClass is a model, pattern, or blueprint from which an object is created. A class describes the objects, their structure and behaviorInstance data or variable (fields) memory space is created for each instance of the class that is created. Variables declared in a class.When you create an object, you are creating an instance of a class. (Copy of the class)Method subprograms that perform a specific task. 2 parts of a method:Method Declaration access level(public or private), return type, name, and parameters. Method Body local variable declaration, statements that implements the method.ClassDeclared publicKeyword classClass name (1st letter of name should be capitalized)Begin Brace {Example:public class Student{When saving a class, it should be saved as the same name as class with the extension .javaClasses and Source FilesThe name of the source file must be exactly the same name as the class (including upper and lowercase letters) with the extension .javaThe Java files for all the classes you create for a project should be located in the same folder.ObjectsIn a well designed OOP program, each object is responsible for its own clearly defined set of tasks. Objects must be easily controlled and not too complicated.Classs ClientAny class that uses class X is called a client of XClass Xprivate fields

private methods

public methods public constructor(s)Class Y

A client of XConstructs objects of X and/or calls Xs methods7The same programmer can develop a class and its client(s).FieldsFields data elements of the class.Fields may hold numbers, characters, strings, or objectsFields act as personal memory of an object and the particular values stored in them determine the objects current state.Each object (instance of a class) has the same fields, but there may be different values stored in those fields.FieldsFields are declared as private or public. In most cases, they are declared privateWhen each variable is created for each object of the class, it is called instance variable.When a field is declared as static, it is called a class variable and only created once and all objects share that memory location.Examples:private int mySum = 10;private static int mySum = 10; //creates one memory location that all the objects shareFields are Global meaning that they can be accessed anywhere in the class including methods.Access Modifiers public and privateVariables or methods declared with access modifier private are accessible only to methods of the class in which they are declared. Public variables or methods can be accessible from outside the class.Data Hiding (encapsulated) The private access modifier allows a programmer to hide memory location from the program and cant be directly changed.Public vs. PrivatePublic constructors and methods of a class constitute its interface with classes that use it its clients.All fields are usually declared private they are hidden from clients.Static constants occasionally can be public.Helper methods that are needed only inside the class are declared private.11Static public constants (for example, Math.PI or Color.BLUE) do not violate the spirit of encapsulation because they are specifically intended to be used by the classs clients.Public vs. Private (contd)A private field is accessible anywhere within the classs source code.Any object can access and modify a private field of another object of the same class.public class Fraction{ private int num, denom; ... public multiply (Fraction other) { int newNum = num * other.num; ...12num is private to the class Fraction. It is totally fine to refer to other.num in Fractions methods.EncapsulationHiding the implementation details of a class (making all fields and helper methods private) is called encapsulation.Encapsulation helps in program maintenance: a change in one class does not affect other classes.A client of a class iteracts with the class only through well-documented public constructors and methods; this facilitates team development.13A programmer tries to minimize what others (clients) need to know about his or her class, even if he/she is one of the others when working on other classes. The idea is to keep things localized, so that if something changes in the implementation of one class, other classes remain unaffected.

Programmers agree on the public interfaces (public constructors and methods) for their classes, then go to work on their classes and often test them separately, too.Encapsulation (contd) public class MyClass { // Private fields: private myField; ...

// Constructors: public MyClass (...) { ... } ... // Public methods: public myMethod (...) { ... } ... // Private methods: private myMethod (...) { ... } ... }Public interface: public constructors and methods14The classs public interface is what other programmers need to know to use the class. (They also might need to know some details about the class's superclass and the interfaces this class implements -- see Chapter 11).ConstructorsConstructor primary purpose is to initialize the objects field.A classs constructor define different ways of creating an object.Different constructor use different numbers or types of parametersConstructors are not called explicitly, but invoked using the new operator.ConstructorsHas the same name as the class.Default constructor automatically created by the compiler if no constructors are present.Default constructor assigns the fields to all default values if they are not initialized.Default values integers and real data fields are set to 0.Objects are set to nullBoolean are set to falseConstructors do not have a return typeConstructorIf a class has more than one constructor, they must have different numbers and/or types of parameters.Constructors allows you to create a set the fields to their starting values.One of the constructors will run when an object of the class is created.Constructors (contd)Programmers often provide a no-args constructor that takes no parameters (a.k.a. arguments).If a programmer does not define any constructors, Java provides one default no-args constructor, which allocates memory and sets fields to the default values.18The default values for fields are as follows: 0 for numbers, false for booleans, and null for objects. Any constructor sets a field to the default, unless the field is explicitly set to some value. If a field is an object, a constructor may create that object by invoking a constructor for that objects class.Constructors (contd)public class Fraction{ private int num, denom;

public Fraction ( ) { num = 0; denom = 1; }

public Fraction (int n) { num = n; denom = 1; } Continued public Fraction (int n, int d) { num = n; denom = d; reduce (); }

public Fraction (Fraction other) { num = other.num; denom = other.denom; } ...

}No-args constructorCopy constructor19This example shows four constructors for the Fraction class, including the no-args constructor and the copy constructor.Constructors (contd)A nasty bug:public class MyWindow extends JFrame{ ... // Constructor: public void MyWindow ( ) { ... } ...Compiles fine, but the compiler thinks this is a method and uses MyWindows default no-args constructor instead.20It is an unfortunate decision in Java to allow a method name that is the same as the name of the class.Constructors (contd)Constructors of a class can call each other using the keyword this a good way to avoid duplicating code:

... public Fraction (int p, int q) { num = p; denom = q; reduce (); } ...

public class Fraction{ ...

public Fraction (int n) { this (n, 1); } ...21If the structure of the fields change, only one constructor will have to be modified. Here we dont gain much by using this, but in other situations where we have longer constructors that are almost identical, we can avoid duplicating a large chunk of code. Easier to debug and test, too. This usage of this is not in the AP subset.Copy ConstructorStudent s1 = new Student();Student s2 = new Student(s1); //copy constructor.NotesDynamic Memory Allocation pool of memory that is drawn from and added to as the program is running.Garbage Collection When the computer is done with an object, it is put into the garbage collection.Variables holds a reference (address) to an object of the corresponding type.It is crucial to initialize a reference before using it.MethodsMethods defines the behavior of an object, what the object can do.It represents what an object of a particular type can do in response to a particular call or message.Method DesignAn algorithm is a step-by-step process for solving a problemExamples: a recipe, travel directionsEvery method implements an algorithm that determines how the method accomplishes its goalsAn algorithm may be expressed in pseudocode, a mixture of code statements and English that communicate the steps to takeMethod DecompositionA method should be relatively small, so that it can be understood as a single entityA potentially large method should be decomposed into several smaller methods as needed for clarityA public service method of an object may call one or more private support methods to help it accomplish it