Class StructureClassesDefining a classDefining fieldsDefining constructorsExample constructor IExample constructor IIDefining a methodMethods may have local variablesBlocks (== Compound statements)Declarations in a methodNested scopesThe for loopReturning a result from a methodReturning no result from a methodSending messages to objectsPutting it all togetherUsing our new classDiagram of program structurenullMethods and static methodsEscaping from staticThe EndJan 14, 2019Class Structure2ClassesA class describes a set of objectsThe objects are called instances of the classA class describes:Fields (instance variables)that hold the data for each objectConstructors that tell how to create a new object of this classMethods that describe the actions the object can performIn addition, a class can have data and methods of its own (not part of the objects)For example, it can keep a count of the number of objects it has createdSuch data and methods are called staticWe are avoiding static data and methods for the time being3Defining a classHere is the simplest syntax for defining a class: class ClassName { // the fields (variables) of the object // the constructors for the object // the methods of the object}You can put public, protected, or private before the word classThings in a class can be in any order (I recommend the above order)4Defining fieldsAn object’s data is stored in fields (also calledinstance variables)The fields describe the state of the objectFields are defined with ordinary variable declarations:String name;Double health;int age = 0;Instance variables are available throughout the entire class that declares them5Defining constructorsA constructor is code to create an objectYou can do other work in a constructor, but you shouldn’tThe syntax for a constructor is: ClassName(parameters) { …code…}The ClassName has to be the same as the class that the constructor occurs inThe parameters are a comma-separated list of variable declarations6Example constructor I public class Person { String name; int age; boolean male; Person (String aName, boolean isMale) { name = aName; male = isMale; }}ConstructorParameters7Example constructor IIMost constructors just set instance variables:public class Person { String name; boolean male; Person (String name, boolean male) { this.name = name ; this.male = male ; }}Defining a methodA method has the syntax: return-type method-name(parameters) { method-variables code}Example: boolean isAdult(int age) { int magicAge = 21; return age >= magicAge;}Example: double average(int a, int b) { return (a + b) / 2.0;}9Methods may have local variablesA method may have local (method) variablesFormal parameters are a kind of local variableint add(int m, int n) { int sum = m + n; return sum;}m, n, and sum are all local variablesThe scope of m, n, and sum is the methodThese variables can only be used in the method, nowhere elseThe names can be re-used elsewhere, for other variables10Blocks (== Compound statements)Inside a method or constructor, whenever you use braces, you are creating a block, or compound statement: int absoluteValue(int n) { if (n < 0) { return -n; } else return n;}11Declarations in a methodThe scope of formal parameters is the entire methodThe scope of a variable in a block starts where you define it and extends to the end of the block if (x > y) { int larger = x;}else { int larger = y;}return larger;largerscope of largerlargerscope of adifferent largerIllegal: not declared in current scope12Nested scopes int fibonacci(int limit) { int first = 1; int second = 1; while (first < 1000) { System.out.print(first + " "); int next = first + second; first = second; second = next; } System.out.println( ); } limitfirstnextsecond13The for loopThe for loop is a special caseYou can declare variables in the for statementThe scope of those variables is the entire for loopThis is true even if the loop is not a block void multiplicationTable() { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) System.out.print(" " + i * j); System.out.println(); } } jiReturning a result from a methodIf a method is to return a result, it must specify the type of the result:boolean isAdult ( …You must use a return statement to exit the method with a result of the correct type:return age >= magicAge;Returning no result from a methodThe keyword void is used to indicate that a method doesn’t return a valueThe return statement must not specify a valueExample:void printAge(String name, int age) { System.out.println(name + " is " + age + " years old."); return;}There are two ways to return from a void method:Execute a return statementReach the closing brace of the method16Sending messages to objectsWe don’t perform operations on objects, we “talk” to themThis is called sending a message to the objectA message looks like this: object.method(extra information)•The object is the thing we are talking to•The method is a name of the action we want the object to take•The extra information is anything required by the method in order to do its jobExamples: g.setColor(Color.pink); amountOfRed = Color.pink.getRed( );17Putting it all together class Person { // fields String name; int age; // constructor Person(String name) { this.name = name; age = 0; } // methods String getName() { return name; } void birthday() { age = age + 1; System.out.println( "Happy birthday!"); } }18Using our new class Person john; john = new Person("John Smith"); System.out.print (john.getName()); System.out.println(" is having a birthday!"); john.birthday();Of course, this code must also be inside a class!19Diagram of program structureA program consists of one or more classesTypically, each class is in a separate .java fileProgramFileFileFileFileClassVariablesConstructorsMethodsVariablesVariablesStatementsStatements20nullIf you declare a variable to have a given object type, for example,Person john;String name;...and if you have not yet assigned a value to it, for example, withjohn = new Person();String name = “John Smith";...then the value of the variable is nullnull is a legal value, but there isn’t much you can do with
View Full Document