1 java programming using methods, classes, and objects

Download 1 Java Programming Using Methods, Classes, and Objects

Post on 02-Jan-2016

213 views

Category:

Documents

1 download

Embed Size (px)

TRANSCRIPT

  • Java ProgrammingUsing Methods, Classes, and Objects

  • Topics:Methods with no arguments, a single argument, multiple argumentswith return valuesClass conceptsCreate a classUse instance methodsDeclare objectsOrganize classesUse constructors

  • MethodA method is a series of statements that carry out a taskAny class can contain an unlimited number of methods

  • MethodsMethods must include:A declarationAn opening curly braceA bodyA closing brace

  • MethodsMethod declarations must contain:Optional access modifiersThe return type for the methodThe method nameAn opening parenthesisAn optional list of method argumentsA closing parenthesis

  • Access ModifiersAccess modifiers for a method can be:public- most often methods are given public accessprivateprotectedstatic

  • Access Modifierspublic- Endowing a method with public access means any class can use itstatic- Any method that can be used from anywhere within the class requires the keyword modifier static

  • Creating Methods that Require a Single ArgumentArguments- Are communications to a method

    Implementation hiding- Allows that the invoking program must know the name of the method and what type of information to send it, but the program does not need to know how the method works

  • Creating Methods that Require a Single ArgumentThe method declaration must include:The type of the argumentA local name for the argumentFor example: public void predictRaise(double moneyAmount)

  • Calling a MethodCan use either argument:ConstantVariablepredictRaise(472.55)predictRaise(mySalary)

  • Creating Methods that Require Multiple ArgumentsMethods can require more than one argumentPass multiple arguments by:Listing the arguments in the call to the methodSeparating them with commasThe declaration for a method that receives two or more arguments must list the type for each argument separately

  • A Methods Return TypeThe return type is known as the methods typeFor example:public static void nameAndAddress()This method is public and returns no value public static String nameAndAddress()This method returns a string (with name and address)

  • Return StatementThe return statement is the last statement in a methodUsually you use the returned value, but this is not required

  • Overloading a MethodOverloading:Involves using one term to indicate diverse meaningsWriting multiple methods with the same name, but with different argumentsOverloading a Java method means you write multiple methods with a shared name

  • Overloaded methodsMethods can be overloaded to support different types of dataOverloaded methods have the same name and return type (the latter is often forgotten)But the number and type of arguments can be changed to support different cases/scenariosFor examplefloat calculateRaise(float Salary, float Raise_Amount );2nd argument represents raise in $ (float)float calculateRaise(float Salary, int Percent_Amount);2nd argument represents raise in percent (integer) float calculateRaise(float Salary);No 2nd argument, standard (constant raise)

  • Learning about Ambiguity When you overload a method you run the risk of ambiguityAn ambiguous situation is one in which the compiler cannot determine which method to useExamples?

  • Overloading Examplestatic float calculateRaise(float empSalary, float payRaise){return empSalary + payRaise;}

    static float calculateRaise(float empSalary, int payRaise){return empSalary * (1 + (float)payRaise/100);}

    public static void main(String[] arg){// why need f after constant System.out.println("1: " + calculateRaise(100000.00f, 3000.00f)); System.out.println("1: " + calculateRaise(100000.00f, 10)); System.out.println("1: " + calculateRaise(100000, 10.0)); //doesnt work}

  • Class ConceptsIn object-oriented programming:Everything is an objectAn object is an instantiation of a class, or a tangible example of a classEvery object is a member of a classYour desk is an object and is a member of the Desk classThese statements represent is-a relationships

  • Class ConceptsThe concept of a class is useful because:Objects inherit attributes from classesAll objects have predictable attributes because they are members of certain classes You must:Create the classes of objects from which objects will be instantiated Write other classes to use the objectsClass Client or Class User-A program or class that instantiates objects of another prewritten class

  • Creating a ClassYou must:Assign a name to the classDetermine what data and methods will be part of the class

    To begin, create a class header with three parts:An optional access modifierThe keyword classAny legal identifier you choose for the name of the class

    The define the class contentsThen add a open and close braceAdd the attributes (fields) and actions (methods) to the class

  • Access modifiers for Classes

    Access modifiers include:public This is the most used modifierMost liberal form of accessCan be extended or used as the basis for other classesfinal- used only under special circumstancesabstract- used only under special circumstances

  • Access modifiers for Fields and MethodsPrivate (default for fields) Public (default for methods)Static Final

  • Field ModifiersPrivate No other classes can access a fields valuesOnly methods of the same class are allowed to set, get, or otherwise use private variablesHighest level of securityAlso called information hidingProvides a means to control outside access to your data

  • Using Instance MethodsMethods used with object instantiations are called instance methodsYou can call class methods without creating an instance of the class.Instance methods require an instantiated object.

  • Declaring ObjectsTo declare an object:Supply a type and an identifierAllocate computer memory for the objectUse the new operator

  • Organizing ClassesMost programmers place data fields in some logical order at the beginning of a classFor example, use a unique identifier for each employeeempNumLast names and first names are organized together

  • Using Constructor MethodsConstructor methods- Methods that establish an objectEmployee chauffer = new Employee();Calls a method named Employee() that is provided by the Java compilerMethods are commonly overloaded to provide various ways to initialize an objectEmployee chauffer = new Employee(Mike Elm);Employee chauffer = new Employee(Mike Elm, 2320);

  • ADVANCED TOPICS

  • Advanced Topics:Understand blocks and scopeLearn about ambiguitySend arguments to constructorsOverload constructorsLearn about the this referenceWork with constantsUse automatically imported, prewritten constants and methodsUse prewritten imported methods

  • Understanding BlocksBlocks-Within any class or method, the code between a pair of curly bracesOutside block- The first block, begins immediately after the method declaration and ends at the end of the method Inside block- The second block, contained within the second pair of curly bracesThe inside block is nested within the outside block

  • Understanding ScopeThe portion of a program within which you can reference a variableA variable comes into existence, or comes into scope, when you declare itA variable ceases to exist, or goes out of scope, at the end of the block in which it is declared

  • public class Test{public static void main(String[] args) throws Exception {while (true){ int Count = 10; . Count++; // this is ok}

    for(int i = 0; i < MAX_NUM; i++){ Count++; // this will generate an error, why?}

    } // end of main}//end of class Test

  • Overriding a Method or VariableIf you declare a variable within a class, and use the same variable name within a method of the class, then the variable used inside the method takes precedence, or overrides, the first variableIn Java you can override variables and methodsVariable overriding is confusing and should be avoidedMethod overriding is useful and necessary

  • ConstructorsJava automatically provides a constructor method when you create a classProgrammers can write their own constructor methodsProgrammers can also write constructors that receive argumentsSuch arguments are often used for initialization purposes when values of objects might vary

  • Overloading ConstructorsIf you create a class from which you instantiate objects, Java automatically provides a constructorBut, if you create your own constructor, the automatically created constructor no longer existsAs with other methods, you can overload constructorsOverloading constructors provides a way to create objects with or without initial arguments, as needed

  • Using the this ReferenceClasses can become large very quicklyEach class can have many data fields and methods

    If you instantiate many objects of a class, the computer memory requirements can become substantialIt is not necessary to store a separate copy of each variable and method for each instantiation of a class

    The compiler accesses the correct objects data fields because you implicitly pass a this reference to class methodsStatic methods, or class methods, do not have a this reference because they have no object associated with them

  • Class VariablesClass variables- Variables that are shared by every instantiation of a classClass variables (and methods) are also refered to as static variables (or methods) because of the access modifier used to define them

  • Working with ConstantsConstant variable:A variable or data field that should not be changed during the execution of a programTo prevent alteration, use the keyword finalConstant fields are written in