Introduction to Computer Science II COSC 1320/6305 Lecture 2: Defining Classes I (Chapter 4)
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Class Participation NetBeans Projects
http://wps.aw.com/aw_savitch_abjava_4s/110/28360/7260312.cw/index.html 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
http://wps.aw.com/aw_savitch_abjava_4s/110/28360/7260312.cw/index.html 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Class Participation NetBeans Projects
Classes and Objects in Java Basics of Classes in Java
Contents Introduce to classes and objects in Java . Understand how some of the OO concepts learnt so far are supported in Java. Understand important features in Java classes .
Introduction Java is a true OO language and therefore the underlying structure of all Java programs is classes . Anything we wish to represent in Java must be encapsulated in a class that defines the “ state ” and “ behaviour ” of the basic program components known as objects . Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them . A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation , inheritance , and polymorphism .
Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()
Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition: Bare bone class – no fields , no methods public class Circle { // my circle class } class ClassName [ extends SuperClassName ] { [ fields declaration ] [ methods declaration ] }
Adding Fields: Class Circle with fields Add fields The fields (data) are also called the instance variables . public class Circle { public double x , y ; // center coordinate public double r ; // radius of the circle }
Adding Methods A class with only data fields has no life . Objects created by such a class cannot respond to any messages . Methods are declared inside the body of the class but immediately after the declaration of data fields . The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }
Adding Methods to Class Circle public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference () { return 2*3.14*r; } public double area () { return 3.14 * r * r; } } Method Body public only for example purposes!!!!
Data Abstraction Declare the Circle class , have created a new data type – Data Abstraction Can define variables ( objects ) of that type: Circle aCircle ; Circle bCircle ;
Class of Circle aCircle , bCircle simply refers to a Circle object , not an object itself . aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null Circle aCircle ; Circle bCircle ;
Creating objects of a class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;
Creating objects of a class aCircle = new Circle() ; bCircle = new Circle() ; bCircle = aCircle ;
Creating objects of a class Q bCircle Before Assignment Q bCircle After Assignment aCircle = new Circle() ; bCircle = new Circle() ; bCircle = aCircle ; P aCircle P aCircle
Automatic garbage collection The object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection . Java automatically collects garbage periodically and releases the memory used to be used in the future. Q
Accessing Object /Circle Data Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle() ; aCircle . x = 2.0; // initialize center and radius aCircle . y = 2.0; aCircle . r = 1.0; ObjectName . V ariableName ObjectName . MethodName (parameter-list)
Executing Methods in Object/Circle Using Object Methods : Circle aCircle = new Circle() ; double area; aCircle . r = 1.0; area = aCircle . area (); sent ‘message’ to aCircle
Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle ; // creating reference aCircle = new Circle() ; // creating object aCircle . x = 10; // assigning value to data field aCircle . y = 20; aCircle . r = 5; double area = aCircle . area() ; // invoking method double circumf = aCircle . circumference (); System.out.println("Radius="+ aCircle . r+" Area="+area); System.out.println("Radius="+ aCircle .r+" Circumference ="+circumf); } } Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002
Summary Classes, objects , and methods are the basic components used in Java programming. We have discussed: How to define a class How to create objects How to add data fields and methods to classes How to access data fields and methods to classes
Introduction Classes are the most important language feature that make object-oriented programming ( OOP ) possible Programming in Java consists of defining a number of classes Every program is a class All helping software consists of classes All programmer-defined types are classes Classes are central to Java 4-
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Class Definitions You already know how to use classes and the objects created from them, and how to invoke their methods For example, you have already been using the predefined String and Scanner classes Now you will learn how to define your own classes and their methods , and how to create your own objects from them 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Class Is a Type A class is a special kind of programmer-defined type, and variables can be declared of a class type A value of a class type is called an object or an instance of the class If A is a class , then the phrases " bla is of type A," " bla is an object of the class A," and " bla is an instance of the class A" mean the same thing A class determines the types of data that an object can contain, as well as the actions it can perform 4- CLASS Participation A!
UML Class Diagram 4-
File Names and Locations Reminder: a Java file must be given the same name as the class it contains with an added .java at the end For example, a class named MyClass must be in a file named MyClass.java For now, your program and all the classes it uses should be in the same directory or folder 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Application Programs A Java application program or "regular" Java program is a class with a method named main When a Java application program is run, the run-time system automatically invokes the method named main All Java application programs start with the main method 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved. CLASS Participation B! (pp. 6)
A Sample Java Application Program 1-
System .out. println Java programs work by having things called objects perform actions System.out : an object used for sending output to the screen The actions performed by an object are called methods println : the method or action that the System.out object performs 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
System .out. println Invoking or calling a method : When an object performs an action using a method Also called sending a message to the object Method invocation syntax (in order): an object , a dot (period) , the method name, and a pair of parentheses Arguments : Zero or more pieces of information needed by the method that are placed inside the parentheses System .out. println ("This is an argument"); 1-
Variable declarations Variable declarations in Java are similar to those in other programming languages ( C ) Simply give the type of the variable followed by its name and a semicolon ; int answer ; 1-
Using = and + In Java , the equal sign ( = ) is used as the assignment operator The v ariable on the left side of the assignment operator = is assigned the value of the expression on the right side of the assignment operator = answer = 2 + 2; In Java , the plus sign ( + ) can be used to denote addition (as above) or concatenation Using + , two strings can be connected together System.out.println("2 plus 2 is " + answer); 1-
Primitive Type Values vs. Class Type Values A primitive type value is a single piece of data A class type value or object can have multiple pieces of data , as well as actions called methods All objects of a class have the same methods All objects of a class have the same pieces of data (i.e., name, type, and number) For a given object , each piece of data can hold a different value 4- CLASS Participation C! (pp. 188)
UML Class Diagram 4-
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Formal Parameter Used as a Local Variable ( BillingDialog.java ) 4-
The new Operator An object of a class is named or declared by a variable of the class type: ClassName classVar ; The new operator must then be used to create the object and associate it with its variable name: classVar = new ClassName(); These can be combined as follows: ClassName classVar = new ClassName(); 4-
Step Into 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The Contents of a Class Definition A class definition specifies the data items and methods that all of its objects will have These data items and methods are sometimes called members of the object Data items are called fields or instance variables Instance variable declarations and method definitions can be placed in any order within the class definition 4-
( Bill.java ) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved. The Contents of a Class Definition
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
( BillingDialog.java ) 4-
Instance Variables Instance variables can be defined as in the following two examples Note the public modifier (for now): public String instanceVar1 ; public int instanceVar2 ; In order to refer to a particular instance variable , preface it with its object name as follows: objectName . instanceVar1 objectName . instanceVar2 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Method definitions are divided into two parts: a heading and a body : public void myMethod() Heading { code to perform some action Body and/or compute a value } Methods are invoked using the name of the calling object and the method name as follows: classVar . myMethod() ; Invoking a method is equivalent to executing the method body Methods 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
( BillingDialog.java ) 4-
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
More About Methods There are two kinds of methods : Methods that compute and return a value Methods that perform an action This type of method does not return a value, and is called a void method Each type of method differs slightly in how it is defined as well as how it is (usually) invoked 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
More About Methods A method that returns a value must specify the type of that value in its heading: public typeReturned methodName (paramList) A void method uses the keyword void in its heading to show that it does not return a value : public void methodName (paramList) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
main is a void Method A program in Java is just a class that has a main method When you give a command to run a Java program , the run-time system invokes the method main Note that main is a void method , as indicated by its heading: public static void main (String[] args)
return Statements The body of both types of methods contains a list of declarations and statements enclosed in a pair of braces public < void or typeReturned > myMethod () { declarations Body statements } 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
return Statements The body of a method that returns a value must also contain one or more return statements A return statement specifies the value returned and ends the method invocation: return Expression; Expression can be any expression that evaluates to something of the type returned listed in the method heading 4-
return Statements A void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed In this context, since it does not return a value, a return statement is used without an expression: return; 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Method Definitions An invocation of a method that returns a value can be used as an expression anyplace that a value of the typeReturned can be used: typeReturned tRVariable; tRVariable = objectName . methodName() ; An invocation of a void method is simply a statement: objectName . methodName() ; 4-
Any Method Can Be Used As a void Method A method that returns a value can also perform an action If you want the action performed, but do not need the returned value, you can invoke the method as if it were a void method , and the returned value will be discarded: objectName . returnedValueMethod() ; 4-
Local Variables A variable declared within a method definition is called a local variable All variables declared in the main method are local variables All method parameters are local variables If two methods each have a local variable of the same name, they are still two entirely different variables 4-
Global Variables Some programming languages include another kind of variable called a global variable The Java language does not have global variables 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Blocks A block is another name for a compound statement, that is, a set of Java statements enclosed in braces, {} A variable declared within a block is local to that block, and cannot be used outside the block Once a variable has been declared within a block, its name cannot be used for anything else within the same method definition 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Declaring Variables in a for Statement You can declare one or more variables within the initialization portion of a for statement A variable so declared will be local to the for loop, and cannot be used outside of the loop If you need to use such a variable outside of a loop, then declare it outside the loop 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
( Bill.java ) 4-
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Parameters of a Primitive Type The methods seen so far have had no parameters, indicated by an empty set of parentheses in the method heading Some methods need to receive additional data via a list of parameters in order to perform their work These parameters are also called formal parameters 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Parameters of a Primitive Type A parameter list provides a description of the data required by a method It indicates the number and types of data pieces needed, the order in which they must be given, and the local name for these pieces as used in the method public double myMethod (int p1, int p2, double p3) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Parameters of a Primitive Type When a method is invoked, the appropriate values must be passed to the method in the form of arguments Arguments are also called actual parameters The number and order of the arguments must exactly match that of the parameter list The type of each argument must be compatible with the type of the corresponding parameter int a=1,b=2,c=3; double result = myMethod(a,b,c) ; 4-
Parameters of a Primitive Type In the preceding example, the value of each argument (not the variable name) is plugged into the corresponding method parameter This method of plugging in arguments for formal parameters is known as the call-by-value mechanism 4-
Parameters of a Primitive Type If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion In the preceding example, the int value of argument c would be cast to a double A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right: byte  short  int  long  float  double char 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Parameters of a Primitive Type A parameter is often thought of as a blank or placeholder that is filled in by the value of its corresponding argument However, a parameter is more than that: it is actually a local variable When a method is invoked, the value of its argument is computed, and the corresponding parameter (i.e., local variable ) is initialized to this value Even if the value of a formal parameter is changed within a method (i.e., it is used as a local variable ) the value of the argument cannot be changed 4-
A Formal Parameter Used as a Local Variable ( Bill.java ) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Pitfall: Use of the Terms &quot; Parameter &quot; and &quot; Argument &quot; Do not be surprised to find that people often use the terms parameter and argument interchangeably When you see these terms, you may have to determine their exact meaning from context 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The this Parameter All instance variables are understood to have < the calling object > . in front of them If an explicit name for the calling object is needed, the keyword this can be used myInstanceVariable always means and is always interchangeable with this . myInstanceVariable 4-
The this Parameter this must be used if a parameter or other local variable with the same name is used in the method Otherwise, all instances of the variable name will be interpreted as local int someVariable = this . someVariable local instance 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The this Parameter The this parameter is a kind of hidden parameter Even though it does not appear on the parameter list of a method , it is still a parameter When a method is invoked, the calling object is automatically plugged in for this 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Formal Parameter Used as a Local Variable ( Bill.java ) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Formal Parameter Used as a Local Variable 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Methods That Return a Boolean Value An invocation of a method that returns a value of type boolean returns either true or false Therefore, it is common practice to use an invocation of such a method to control statements and loops where a Boolean expression is expected if-else statements, while loops, etc. 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The methods equals and toString Java expects certain methods , such as equals and toString , to be in all, or almost all, classes The purpose of equals , a boolean valued method , is to compare two objects of the class to see if they satisfy the notion of &quot;being equal“ Note: You cannot use == to compare objects public boolean equals (ClassName objectName ) The purpose of the toString method is to return a String value that represents the data in the object public String toString() 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Testing Methods Each method should be tested in a program in which it is the only untested program A program whose only purpose is to test a method is called a driver program One method often invokes other methods , so one way to do this is to first test all the methods invoked by that method , and then test the method itself This is called bottom-up testing Sometimes it is necessary to test a method before another method it depends on is finished or tested In this case, use a simplified version of the method , called a stub , to return a value for testing 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been fully tested and debugged 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Information Hiding and Encapsulation Information hiding is the practice of separating how to use a class from the details of its implementation Abstraction is another term used to express the concept of discarding details in order to avoid information overload Encapsulation means that the data and methods of a class are combined into a single unit (i.e., a class object ), which hides the implementation details Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface In Java , hiding details is done by marking them private 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Encapsulation 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Couple of Important Acronyms: API and ADT The API or a pplication p rogramming i nterface for a class is a description of how to use the class A programmer need only read the API in order to use a well designed class An ADT or abstract data type is a data type that is written using good information-hiding techniques 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
public and private Modifiers The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class It is considered good programming practice to make all instance variables private Most methods are public , and thus provide controlled access to the object Usually, methods are private only if used as helping methods for other methods in the class 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Accessor and Mutator Methods Accessor methods allow the programmer to obtain the value of an object 's instance variables The data can be accessed but not changed The name of an accessor method typically starts with the word get Mutator methods allow the programmer to change the value of an object 's instance variables in a controlled manner Incoming data is typically tested and/or filtered The name of a mutator method typically starts with the word set 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Class Has Access to Private Members of All Objects of the Class Within the definition of a class , private members of any object of the class can be accessed, not just private members of the calling object 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Preconditions and Postconditions The precondition of a method states what is assumed to be true when the method is called The postcondition of a method states what will be true after the method is executed, as long as the precondition holds It is a good practice to always think in terms of preconditions and postconditions when designing a method , and when writing the method comment 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Overloading Overloading is when two or more methods in the same class have the same method name To be valid, any two definitions of the method name must have different signatures A signature consists of the name of a method together with its parameter list Differing signatures must have different numbers and/or types of parameters 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Overloading and Automatic Type Conversion If Java cannot find a method signature that exactly matches a method invocation, it will try to use automatic type conversion The interaction of overloading and automatic type conversion can have unintended results In some cases of overloading , because of automatic type conversion, a single method invocation can be resolved in multiple ways Ambiguous method invocations will produce an error in Java 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Pitfall: You Can Not Overload Based on the Type Returned The signature of a method only includes the method name and its parameter types The signature does not include the type returned Java does not permit methods with the same name and different return types in the same class 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
You Can Not Overload Operators in Java Although many programming languages, such as C++ , allow you to overload operators ( + , - , etc.), Java does not permit this You may only use a method name and ordinary method syntax to carry out the operations you desire 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object : public ClassName (anyParameters) { Code } A constructor must have the same name as the class A constructor has no type returned, not even void Constructors are typically overloaded 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Constructors A constructor is called when an object of the class is created using new ClassName objectName = new ClassName (anyArgs); The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator This is the only valid way to invoke a constructor : a constructor cannot be invoked like an ordinary method If a constructor is invoked again (using new ), the first object is discarded and an entirely new object is created If you need to change the values of instance variables of the object , use mutator methods instead 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
You Can Invoke Another Method in a Constructor The first action taken by a constructor is to create an object with instance variables Therefore, it is legal to invoke another method within the definition of a constructor , since it has the newly created object as its calling object For example, mutator methods can be used to set the values of the instance variables It is even possible for one constructor to invoke another 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
A Constructor Has a this Parameter Like any ordinary method , every constructor has a this parameter The this parameter can be used explicitly, but is more often understood to be there than written down The first action taken by a constructor is to automatically create an object with instance variables Then within the definition of a constructor , the this parameter refers to the object created by the constructor 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Include a No-Argument Constructor If you do not include any constructors in your class , Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor in your class , Java will not provide this default constructor If you include any constructors in your class , be sure to provide your own no-argument constructor as well 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Default Variable Initializations Instance variables are automatically initialized in Java boolean types are initialized to false Other primitives are initialized to the zero of their type Class types are initialized to null However, it is a better practice to explicitly initialize instance variables in a constructor Note: Local variables are not automatically initialized 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
The StringTokenizer Class The StringTokenizer class is used to recover the words or tokens in a multi-word String You can use whitespace characters to separate each token, or you can specify the characters you wish to use as separators In order to use the StringTokenizer class , be sure to include the following at the start of the file: import java.util.StringTokenizer; 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Some Methods in the StringTokenizer Class (Part 1 of 2) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Some Methods in the StringTokenizer Class (Part 2 of 2) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Lecture 2 classes i

  • 1.
    Introduction to ComputerScience II COSC 1320/6305 Lecture 2: Defining Classes I (Chapter 4)
  • 2.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 3.
  • 4.
  • 5.
    http://wps.aw.com/aw_savitch_abjava_4s/110/28360/7260312.cw/index.html 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 6.
  • 7.
    Classes and Objects in Java Basics of Classes in Java
  • 8.
    Contents Introduce to classes and objects in Java . Understand how some of the OO concepts learnt so far are supported in Java. Understand important features in Java classes .
  • 9.
    Introduction Java isa true OO language and therefore the underlying structure of all Java programs is classes . Anything we wish to represent in Java must be encapsulated in a class that defines the “ state ” and “ behaviour ” of the basic program components known as objects . Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them . A class essentially serves as a template for an object and behaves like a basic data type “int”. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation , inheritance , and polymorphism .
  • 10.
    Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()
  • 11.
    Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition: Bare bone class – no fields , no methods public class Circle { // my circle class } class ClassName [ extends SuperClassName ] { [ fields declaration ] [ methods declaration ] }
  • 12.
    Adding Fields: Class Circle with fields Add fields The fields (data) are also called the instance variables . public class Circle { public double x , y ; // center coordinate public double r ; // radius of the circle }
  • 13.
    Adding MethodsA class with only data fields has no life . Objects created by such a class cannot respond to any messages . Methods are declared inside the body of the class but immediately after the declaration of data fields . The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }
  • 14.
    Adding Methods to Class Circle public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference () { return 2*3.14*r; } public double area () { return 3.14 * r * r; } } Method Body public only for example purposes!!!!
  • 15.
    Data Abstraction Declarethe Circle class , have created a new data type – Data Abstraction Can define variables ( objects ) of that type: Circle aCircle ; Circle bCircle ;
  • 16.
    Class of Circle aCircle , bCircle simply refers to a Circle object , not an object itself . aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null Circle aCircle ; Circle bCircle ;
  • 17.
    Creating objects of a class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;
  • 18.
    Creating objects of a class aCircle = new Circle() ; bCircle = new Circle() ; bCircle = aCircle ;
  • 19.
    Creating objects of a class Q bCircle Before Assignment Q bCircle After Assignment aCircle = new Circle() ; bCircle = new Circle() ; bCircle = aCircle ; P aCircle P aCircle
  • 20.
    Automatic garbage collectionThe object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection . Java automatically collects garbage periodically and releases the memory used to be used in the future. Q
  • 21.
    Accessing Object/Circle Data Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle() ; aCircle . x = 2.0; // initialize center and radius aCircle . y = 2.0; aCircle . r = 1.0; ObjectName . V ariableName ObjectName . MethodName (parameter-list)
  • 22.
    Executing Methods in Object/Circle Using Object Methods : Circle aCircle = new Circle() ; double area; aCircle . r = 1.0; area = aCircle . area (); sent ‘message’ to aCircle
  • 23.
    Using Circle Class// Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle ; // creating reference aCircle = new Circle() ; // creating object aCircle . x = 10; // assigning value to data field aCircle . y = 20; aCircle . r = 5; double area = aCircle . area() ; // invoking method double circumf = aCircle . circumference (); System.out.println(&quot;Radius=&quot;+ aCircle . r+&quot; Area=&quot;+area); System.out.println(&quot;Radius=&quot;+ aCircle .r+&quot; Circumference =&quot;+circumf); } } Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002
  • 24.
    Summary Classes, objects , and methods are the basic components used in Java programming. We have discussed: How to define a class How to create objects How to add data fields and methods to classes How to access data fields and methods to classes
  • 25.
    Introduction Classes are the most important language feature that make object-oriented programming ( OOP ) possible Programming in Java consists of defining a number of classes Every program is a class All helping software consists of classes All programmer-defined types are classes Classes are central to Java 4-
  • 26.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 27.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 28.
    Class Definitions Youalready know how to use classes and the objects created from them, and how to invoke their methods For example, you have already been using the predefined String and Scanner classes Now you will learn how to define your own classes and their methods , and how to create your own objects from them 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 29.
    A Class Is a Type A class is a special kind of programmer-defined type, and variables can be declared of a class type A value of a class type is called an object or an instance of the class If A is a class , then the phrases &quot; bla is of type A,&quot; &quot; bla is an object of the class A,&quot; and &quot; bla is an instance of the class A&quot; mean the same thing A class determines the types of data that an object can contain, as well as the actions it can perform 4- CLASS Participation A!
  • 30.
  • 31.
    File Names andLocations Reminder: a Java file must be given the same name as the class it contains with an added .java at the end For example, a class named MyClass must be in a file named MyClass.java For now, your program and all the classes it uses should be in the same directory or folder 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 32.
    Java Application ProgramsA Java application program or &quot;regular&quot; Java program is a class with a method named main When a Java application program is run, the run-time system automatically invokes the method named main All Java application programs start with the main method 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved. CLASS Participation B! (pp. 6)
  • 33.
    A Sample Java Application Program 1-
  • 34.
    System .out. printlnJava programs work by having things called objects perform actions System.out : an object used for sending output to the screen The actions performed by an object are called methods println : the method or action that the System.out object performs 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 35.
    System .out. printlnInvoking or calling a method : When an object performs an action using a method Also called sending a message to the object Method invocation syntax (in order): an object , a dot (period) , the method name, and a pair of parentheses Arguments : Zero or more pieces of information needed by the method that are placed inside the parentheses System .out. println (&quot;This is an argument&quot;); 1-
  • 36.
    Variable declarations Variable declarations in Java are similar to those in other programming languages ( C ) Simply give the type of the variable followed by its name and a semicolon ; int answer ; 1-
  • 37.
    Using = and + In Java , the equal sign ( = ) is used as the assignment operator The v ariable on the left side of the assignment operator = is assigned the value of the expression on the right side of the assignment operator = answer = 2 + 2; In Java , the plus sign ( + ) can be used to denote addition (as above) or concatenation Using + , two strings can be connected together System.out.println(&quot;2 plus 2 is &quot; + answer); 1-
  • 38.
    Primitive Type Values vs. Class Type Values A primitive type value is a single piece of data A class type value or object can have multiple pieces of data , as well as actions called methods All objects of a class have the same methods All objects of a class have the same pieces of data (i.e., name, type, and number) For a given object , each piece of data can hold a different value 4- CLASS Participation C! (pp. 188)
  • 39.
  • 40.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 41.
    A Formal ParameterUsed as a Local Variable ( BillingDialog.java ) 4-
  • 42.
    The new Operator An object of a class is named or declared by a variable of the class type: ClassName classVar ; The new operator must then be used to create the object and associate it with its variable name: classVar = new ClassName(); These can be combined as follows: ClassName classVar = new ClassName(); 4-
  • 43.
    Step Into 4-Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 44.
    The Contents ofa Class Definition A class definition specifies the data items and methods that all of its objects will have These data items and methods are sometimes called members of the object Data items are called fields or instance variables Instance variable declarations and method definitions can be placed in any order within the class definition 4-
  • 45.
    ( Bill.java )4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved. The Contents of a Class Definition
  • 46.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 47.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 48.
  • 49.
    Instance Variables Instance variables can be defined as in the following two examples Note the public modifier (for now): public String instanceVar1 ; public int instanceVar2 ; In order to refer to a particular instance variable , preface it with its object name as follows: objectName . instanceVar1 objectName . instanceVar2 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 50.
    Method definitionsare divided into two parts: a heading and a body : public void myMethod() Heading { code to perform some action Body and/or compute a value } Methods are invoked using the name of the calling object and the method name as follows: classVar . myMethod() ; Invoking a method is equivalent to executing the method body Methods 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 51.
  • 52.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 53.
    More About Methods There are two kinds of methods : Methods that compute and return a value Methods that perform an action This type of method does not return a value, and is called a void method Each type of method differs slightly in how it is defined as well as how it is (usually) invoked 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 54.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 55.
    More About Methods A method that returns a value must specify the type of that value in its heading: public typeReturned methodName (paramList) A void method uses the keyword void in its heading to show that it does not return a value : public void methodName (paramList) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 56.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 57.
    main isa void Method A program in Java is just a class that has a main method When you give a command to run a Java program , the run-time system invokes the method main Note that main is a void method , as indicated by its heading: public static void main (String[] args)
  • 58.
    return StatementsThe body of both types of methods contains a list of declarations and statements enclosed in a pair of braces public < void or typeReturned > myMethod () { declarations Body statements } 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 59.
    return StatementsThe body of a method that returns a value must also contain one or more return statements A return statement specifies the value returned and ends the method invocation: return Expression; Expression can be any expression that evaluates to something of the type returned listed in the method heading 4-
  • 60.
    return StatementsA void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed In this context, since it does not return a value, a return statement is used without an expression: return; 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 61.
    Method DefinitionsAn invocation of a method that returns a value can be used as an expression anyplace that a value of the typeReturned can be used: typeReturned tRVariable; tRVariable = objectName . methodName() ; An invocation of a void method is simply a statement: objectName . methodName() ; 4-
  • 62.
    Any Method Can Be Used As a void Method A method that returns a value can also perform an action If you want the action performed, but do not need the returned value, you can invoke the method as if it were a void method , and the returned value will be discarded: objectName . returnedValueMethod() ; 4-
  • 63.
    Local Variables Avariable declared within a method definition is called a local variable All variables declared in the main method are local variables All method parameters are local variables If two methods each have a local variable of the same name, they are still two entirely different variables 4-
  • 64.
    Global Variables Someprogramming languages include another kind of variable called a global variable The Java language does not have global variables 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 65.
    Blocks A block is another name for a compound statement, that is, a set of Java statements enclosed in braces, {} A variable declared within a block is local to that block, and cannot be used outside the block Once a variable has been declared within a block, its name cannot be used for anything else within the same method definition 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 66.
    Declaring Variables ina for Statement You can declare one or more variables within the initialization portion of a for statement A variable so declared will be local to the for loop, and cannot be used outside of the loop If you need to use such a variable outside of a loop, then declare it outside the loop 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 67.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 68.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 69.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 70.
  • 71.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 72.
    Parameters ofa Primitive Type The methods seen so far have had no parameters, indicated by an empty set of parentheses in the method heading Some methods need to receive additional data via a list of parameters in order to perform their work These parameters are also called formal parameters 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 73.
    Parameters of aPrimitive Type A parameter list provides a description of the data required by a method It indicates the number and types of data pieces needed, the order in which they must be given, and the local name for these pieces as used in the method public double myMethod (int p1, int p2, double p3) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 74.
    Parameters of aPrimitive Type When a method is invoked, the appropriate values must be passed to the method in the form of arguments Arguments are also called actual parameters The number and order of the arguments must exactly match that of the parameter list The type of each argument must be compatible with the type of the corresponding parameter int a=1,b=2,c=3; double result = myMethod(a,b,c) ; 4-
  • 75.
    Parameters of a Primitive Type In the preceding example, the value of each argument (not the variable name) is plugged into the corresponding method parameter This method of plugging in arguments for formal parameters is known as the call-by-value mechanism 4-
  • 76.
    Parameters of aPrimitive Type If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion In the preceding example, the int value of argument c would be cast to a double A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right: byte  short  int  long  float  double char 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 77.
    Parameters of aPrimitive Type A parameter is often thought of as a blank or placeholder that is filled in by the value of its corresponding argument However, a parameter is more than that: it is actually a local variable When a method is invoked, the value of its argument is computed, and the corresponding parameter (i.e., local variable ) is initialized to this value Even if the value of a formal parameter is changed within a method (i.e., it is used as a local variable ) the value of the argument cannot be changed 4-
  • 78.
    A FormalParameter Used as a Local Variable ( Bill.java ) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 79.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 80.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 81.
    4- Copyright ©2010 Pearson Addison-Wesley. All rights reserved.
  • 82.
    Pitfall: Useof the Terms &quot; Parameter &quot; and &quot; Argument &quot; Do not be surprised to find that people often use the terms parameter and argument interchangeably When you see these terms, you may have to determine their exact meaning from context 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 83.
    The this Parameter All instance variables are understood to have < the calling object > . in front of them If an explicit name for the calling object is needed, the keyword this can be used myInstanceVariable always means and is always interchangeable with this . myInstanceVariable 4-
  • 84.
    The this Parameter this must be used if a parameter or other local variable with the same name is used in the method Otherwise, all instances of the variable name will be interpreted as local int someVariable = this . someVariable local instance 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 85.
    The this Parameter The this parameter is a kind of hidden parameter Even though it does not appear on the parameter list of a method , it is still a parameter When a method is invoked, the calling object is automatically plugged in for this 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 86.
    A FormalParameter Used as a Local Variable ( Bill.java ) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 87.
    A FormalParameter Used as a Local Variable 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 88.
    Methods ThatReturn a Boolean Value An invocation of a method that returns a value of type boolean returns either true or false Therefore, it is common practice to use an invocation of such a method to control statements and loops where a Boolean expression is expected if-else statements, while loops, etc. 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 89.
    The methods equals and toString Java expects certain methods , such as equals and toString , to be in all, or almost all, classes The purpose of equals , a boolean valued method , is to compare two objects of the class to see if they satisfy the notion of &quot;being equal“ Note: You cannot use == to compare objects public boolean equals (ClassName objectName ) The purpose of the toString method is to return a String value that represents the data in the object public String toString() 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 90.
    Testing MethodsEach method should be tested in a program in which it is the only untested program A program whose only purpose is to test a method is called a driver program One method often invokes other methods , so one way to do this is to first test all the methods invoked by that method , and then test the method itself This is called bottom-up testing Sometimes it is necessary to test a method before another method it depends on is finished or tested In this case, use a simplified version of the method , called a stub , to return a value for testing 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 91.
    The Fundamental Rulefor Testing Methods Every method should be tested in a program in which every other method in the testing program has already been fully tested and debugged 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 92.
    Information Hiding and Encapsulation Information hiding is the practice of separating how to use a class from the details of its implementation Abstraction is another term used to express the concept of discarding details in order to avoid information overload Encapsulation means that the data and methods of a class are combined into a single unit (i.e., a class object ), which hides the implementation details Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface In Java , hiding details is done by marking them private 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 93.
    Encapsulation 4- Copyright© 2010 Pearson Addison-Wesley. All rights reserved.
  • 94.
    A Couple ofImportant Acronyms: API and ADT The API or a pplication p rogramming i nterface for a class is a description of how to use the class A programmer need only read the API in order to use a well designed class An ADT or abstract data type is a data type that is written using good information-hiding techniques 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 95.
    public and private Modifiers The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class It is considered good programming practice to make all instance variables private Most methods are public , and thus provide controlled access to the object Usually, methods are private only if used as helping methods for other methods in the class 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 96.
    Accessor and Mutator Methods Accessor methods allow the programmer to obtain the value of an object 's instance variables The data can be accessed but not changed The name of an accessor method typically starts with the word get Mutator methods allow the programmer to change the value of an object 's instance variables in a controlled manner Incoming data is typically tested and/or filtered The name of a mutator method typically starts with the word set 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 97.
    A Class Has Access to Private Members of All Objects of the Class Within the definition of a class , private members of any object of the class can be accessed, not just private members of the calling object 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 98.
    Preconditions and PostconditionsThe precondition of a method states what is assumed to be true when the method is called The postcondition of a method states what will be true after the method is executed, as long as the precondition holds It is a good practice to always think in terms of preconditions and postconditions when designing a method , and when writing the method comment 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 99.
    Overloading Overloading is when two or more methods in the same class have the same method name To be valid, any two definitions of the method name must have different signatures A signature consists of the name of a method together with its parameter list Differing signatures must have different numbers and/or types of parameters 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 100.
    Overloading andAutomatic Type Conversion If Java cannot find a method signature that exactly matches a method invocation, it will try to use automatic type conversion The interaction of overloading and automatic type conversion can have unintended results In some cases of overloading , because of automatic type conversion, a single method invocation can be resolved in multiple ways Ambiguous method invocations will produce an error in Java 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 101.
    Pitfall: YouCan Not Overload Based on the Type Returned The signature of a method only includes the method name and its parameter types The signature does not include the type returned Java does not permit methods with the same name and different return types in the same class 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 102.
    You Can Not Overload Operators in Java Although many programming languages, such as C++ , allow you to overload operators ( + , - , etc.), Java does not permit this You may only use a method name and ordinary method syntax to carry out the operations you desire 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 103.
    Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object : public ClassName (anyParameters) { Code } A constructor must have the same name as the class A constructor has no type returned, not even void Constructors are typically overloaded 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 104.
    Constructors A constructor is called when an object of the class is created using new ClassName objectName = new ClassName (anyArgs); The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator This is the only valid way to invoke a constructor : a constructor cannot be invoked like an ordinary method If a constructor is invoked again (using new ), the first object is discarded and an entirely new object is created If you need to change the values of instance variables of the object , use mutator methods instead 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 105.
    You Can Invoke Another Method in a Constructor The first action taken by a constructor is to create an object with instance variables Therefore, it is legal to invoke another method within the definition of a constructor , since it has the newly created object as its calling object For example, mutator methods can be used to set the values of the instance variables It is even possible for one constructor to invoke another 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 106.
    A Constructor Has a this Parameter Like any ordinary method , every constructor has a this parameter The this parameter can be used explicitly, but is more often understood to be there than written down The first action taken by a constructor is to automatically create an object with instance variables Then within the definition of a constructor , the this parameter refers to the object created by the constructor 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 107.
    Include a No-Argument Constructor If you do not include any constructors in your class , Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor in your class , Java will not provide this default constructor If you include any constructors in your class , be sure to provide your own no-argument constructor as well 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 108.
    Default Variable InitializationsInstance variables are automatically initialized in Java boolean types are initialized to false Other primitives are initialized to the zero of their type Class types are initialized to null However, it is a better practice to explicitly initialize instance variables in a constructor Note: Local variables are not automatically initialized 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 109.
    The StringTokenizer Class The StringTokenizer class is used to recover the words or tokens in a multi-word String You can use whitespace characters to separate each token, or you can specify the characters you wish to use as separators In order to use the StringTokenizer class , be sure to include the following at the start of the file: import java.util.StringTokenizer; 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 110.
    Some Methods in the StringTokenizer Class (Part 1 of 2) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  • 111.
    Some Methods in the StringTokenizer Class (Part 2 of 2) 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.