1 / 68

Classes, Methods, & Objects

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

kedem
Download Presentation

Classes, Methods, & Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Classes, Methods, & Objects

  2. 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 • Learn how parameters are passed to constructors and methods and how to return values from methods • Learn about static and instance fields and methods • Learn about method overloading. • Learn about the copy constructor. • Learn about encapsulation .

  3. Terminology • Class – is a model, pattern, or blueprint from which an object is created. A class describes the objects, their structure and behavior • Instance 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.

  4. Class • Declared public • Keyword class • Class 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 .java

  5. Classes and Source Files • The name of the source file must be exactly the same name as the class (including upper and lowercase letters) with the extension .java • The Java files for all the classes you create for a project should be located in the same folder.

  6. Objects • In 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.

  7. Class’s Client • Any class that uses class X is called a client of X Class X private fields private methods Class Y A client of X public constructor(s) Constructs objects of X and/or calls X’s methods public methods

  8. Fields • Fields – data elements of the class. • Fields may hold numbers, characters, strings, or objects • Fields act as personal memory of an object and the particular values stored in them determine the object’s current state. • Each object (instance of a class) has the same fields, but there may be different values stored in those fields.

  9. Fields • Fields are declared as private or public. In most cases, they are declared private • When 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 intmySum = 10; • private static intmySum = 10; //creates one memory location that all the objects share • Fields are Global meaning that they can be accessed anywhere in the class including methods.

  10. Access Modifiers public and private • Variables 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 can’t be directly changed.

  11. Public vs. Private • Public 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.

  12. Public vs. Private (cont’d) • A private field is accessible anywhere within the class’s source code. • Any object can access and modify a private field of another object of the same class. public class Fraction { privateint num, denom; ... public multiply (Fraction other) { intnewNum = num * other.num; ...

  13. Encapsulation • Hiding 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.

  14. Encapsulation (cont’d) public class MyClass { // Private fields: private <sometype> myField; ... // Constructors: publicMyClass (...) { ... } ... // Public methods: public <sometype> myMethod (...) { ... } ... // Private methods: private <sometype> myMethod (...) { ... } ... } Public interface: public constructors and methods

  15. Constructors • Constructor primary purpose is to initialize the object’s field. • A class’s constructor define different ways of creating an object. • Different constructor use different numbers or types of parameters • Constructors are not called explicitly, but invoked using the new operator.

  16. Constructors • Has 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 null • Boolean – are set to false • Constructors do not have a return type

  17. Constructor • If 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.

  18. Constructors (cont’d) • 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.

  19. Constructors (cont’d) 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” constructor Copy constructor

  20. Constructors (cont’d) • A nasty bug: public class MyWindow extends JFrame { ... // Constructor: public void MyWindow ( ) { ... } ... Compiles fine, but the compiler thinks this is a method and uses MyWindow’s default no-args constructor instead because of void being there.

  21. Constructors (cont’d) • Constructors of a class can call each other using the keyword this — a good way to avoid duplicating code: public class Fraction { ... public Fraction (int n) { this (n, 1); } ... ... public Fraction (int p, int q) { num = p; denom = q; reduce (); } ...

  22. Copy Constructor • Student s1 = new Student(); • Student s2 = new Student(s1); //copy constructor.

  23. Notes • Dynamic 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.

  24. Methods • Methods – 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.

  25. Method Design • An algorithm is a step-by-step process for solving a problem • Examples: a recipe, travel directions • Every method implements an algorithm that determines how the method accomplishes its goals • An algorithm may be expressed in pseudocode, a mixture of code statements and English that communicate the steps to take

  26. Method Decomposition • A method should be relatively small, so that it can be understood as a single entity • A potentially large method should be decomposed into several smaller methods as needed for clarity • A public service method of an object may call one or more private support methods to help it accomplish its goal • Support methods might call other support methods if appropriate

  27. Accessors and Modifiers • A programmer often provides methods, called accessors, that return values of private fields; methods that set values of private fields are called modifiers (Mutator). • Accessors’ names often start with get, and modifiers’ names often start with set. • These are not precise categories: the same method can modify several fields or modify a field and also return its old or new value.

  28. Methods public [or private] returnTypemethodName(type1 name1, ...,typeNnameN) { ... } • To define a method: • decide between public and private (usually public) • give it a name • specify the types of parameters and give them names • specify the method’s return type or chose void • write the method’s code Body Header

  29. Methods (cont’d) • A method is always defined inside a class. • A method returns a value of the specified type unless it is declared void; the return type can be any primitive data type or a class type. • A method’s parameters can be of any primitive data types or class types. Empty parentheses indicate that a method takes no parameters public [or private] returnTypemethodName( ) { ... }

  30. Methods: Java Style • A method name starts with a lowercase letter. • Method names usually sound like verbs. • The name of a method that returns the value of a field often starts with get: getWidth, getX • The name of a method that sets the value of a field often starts with set: setLocation, setText

  31. Static Fields and methods • Two types of variables • Instance variables – non-static • Class variable – static • Static fields are called static because their memory is not dynamically allocated. Memory for static fields is reserved even before any object of the class have been created. • Static methods are not allowed to access or set any non-static methods of the same class. • Instance methods (non-static) can access and change both static and non-static fields.

  32. Static Fields • static fields are shared by all instance of the class. • Example: private static final String letters =“ABCD”; • Static fields are stored separately from instance of the class in a special memory space allocated for the class as a whole.

  33. Static fields continued • Static simply saves space in memory. • The code for methods is not duplicated either: all instances of the same class share code for its method. • All final variables should be declared static because there is no reason to duplicate them. • Example: Private static final int sum = 8;

  34. Static Fields • A static field (a.k.a. class field or class variable) is shared by all objects of the class. • A non-static field (a.k.a. instance field or instance variable) belongs to an individual object.

  35. Static Fields (cont’d) • A static field can hold a constant shared by all objects of the class: • A static field can be used to collect statistics or totals for all objects of the class (for example, total sales for all vending machines) public class RollingDie { private static final double slowDown = 0.97; private static final double speedFactor = 0.04; ... Reserved words: static final

  36. Static Fields (cont’d) • Static fields are stored with the class code, separately from instance variables that describe an individual object. • Public static fields, usually global constants, are referred to in other classes using “dot notation”: ClassName.constName double area = Math.PI * r * r; setBackground(Color.BLUE); c.add(btn, BorderLayout.NORTH); System.out.println(area);

  37. Static Fields (cont’d) • Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods). • If a class has only static fields, there is no point in creating objects of that class (all of them would be identical). • Math and System are examples of the above. They have no public constructors and cannot be instantiated.

  38. Static Methods • Static methods can access and manipulate a class’s static fields. • Static methods cannot access non-static fields or call non-static methods of the class. • Static methods are called using “dot notation”: ClassName.statMethod(...) double x = Math.random(); double y = Math.sqrt (x);

  39. Static Methods (cont’d) public class MyClass { public static final intstatConst; private staticintstatVar; private intinstVar; ... public staticintstatMethod(...) { statVar = statConst; statMethod2(...); instVar = ...; instMethod(...); } Static method OK Errors! instVar &instMethod are not a static variable or Method

  40. Static Methods (cont’d) • main is static and therefore cannot access non-static fields or call non-static methods of its class: public class Hello { private int test () { ... } public static void main (String[ ] args) { System.out.println (test ()); } } Error: non-static method test is called from static context (main)

  41. Static Methods class Helper { public static int cube (int num) { return num * num * num; } } Because it is declared as static, the method can be invoked as value = Helper.cube(5);

  42. Static Class Members • The order of the modifiers can be interchanged, but by convention visibility modifiers come first • Recall that the main method is static – it is invoked by the Java interpreter without creating an object • Static methods cannot reference instance variables because instance variables don't exist until an object exists • However, a static method can reference static variables or local variables

  43. OOP Model • OOP program maintains a world of interacting objects • Describe the different types of objects • What they can do • How they are created • How they interact with other objects.

  44. Operator new • Constructors are invoked using the operator new. • Parameters passed to new must match the number, types, and order of parameters expected by one of the constructors. public class Fraction { public Fraction (int n) { num = n; denom = 1; } ... • Fraction f1 = new Fraction ( ); • Fraction f2 = new Fraction (5); • Fraction f3 = new Fraction (4, 6); • Fraction f4 = new Fraction (f3); 5 / 1

  45. Operator new (cont’d) • You must create an object before you can use it; the new operator is a way to do it. • private Fraction ratio; • ... • ratio = new Fraction (2, 3); • ... • ratio = new Fraction (3, 4); ratio is set to null Now ratio refers to a valid object Now ratio refers to another object (the old object is “garbage-collected”)

  46. f1 f1 A Fraction object: num = 3 denom = 7 A Fraction object: num = 3 denom = 7 A Fraction object: num = 3 denom = 7 f2 References to Objects Fraction f1 = new Fraction(3,7); Fraction f2 = new Fraction(3,7); Fraction f1 = new Fraction(3,7); Fraction f2 = f1; f2 Refer to the same object

  47. Passing Parameters to Constructors and Methods • Any expression that has an appropriate data type can serve as a parameter: double u = 3, v = -4; ... Polynomial p = new Polynomial (1.0, -(u + v), u * v); double y = p.getValue (2 * v - u); public class Polynomial { public Polynomial (double a, double b, double c) { ... } public double getValue (double x) { ... } ...

  48. Passing Parameters (cont’d) • A “smaller” type can be promoted to a “larger” type (for example, int to long, float to double). • int is promoted to double when necessary: ... Polynomial p = new Polynomial (1, -5, 6); double y = p.getValue (3); The same as: (1.0, -5.0, 6.0) The same as: (3.0)

  49. Passing Parameters (cont’d) • Primitive data types are always passed “by value”: the value is copied into the parameter. public class Polynomial { ... public double getValue (double u) { double v; ... } } copy double x = 3.0; double y = p.getValue ( x ); u acts like a local variable in getValue x: 3.0 u:3.0 copy

  50. Passing Parameters (cont’d) public class Test { public double square (double x) { x *= x; return x; } public static void main(String[ ] args) { Test calc = new Test (); double x = 3.0; double y = calc.square (x); System.out.println (x + " " + y); } } x here is a copy of the parameter passed to square. The copy is changed, but... ... the original x is unchanged. Output: 3 9

More Related