DOC PREVIEW
Penn CIT 591 - Class Structure

This preview shows page 1-2-22-23 out of 23 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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 Structure2ClassesA class describes a set of objectsThe objects are called instances of the classA class describes:Fields (instance variables)that hold the data for each objectConstructors that tell how to create a new object of this classMethods that describe the actions the object can performIn 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 createdSuch data and methods are called staticWe are avoiding static data and methods for the time being3Defining a classHere 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 classThings in a class can be in any order (I recommend the above order)4Defining fieldsAn object’s data is stored in fields (also calledinstance variables)The fields describe the state of the objectFields are defined with ordinary variable declarations:String name;Double health;int age = 0;Instance variables are available throughout the entire class that declares them5Defining constructorsA constructor is code to create an objectYou can do other work in a constructor, but you shouldn’tThe syntax for a constructor is: ClassName(parameters) { …code…}The ClassName has to be the same as the class that the constructor occurs inThe 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 IIMost 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 methodA 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 variablesA method may have local (method) variablesFormal parameters are a kind of local variableint add(int m, int n) { int sum = m + n; return sum;}m, n, and sum are all local variablesThe scope of m, n, and sum is the methodThese variables can only be used in the method, nowhere elseThe 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 methodThe scope of formal parameters is the entire methodThe 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 loopThe for loop is a special caseYou can declare variables in the for statementThe scope of those variables is the entire for loopThis 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 methodIf 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 methodThe keyword void is used to indicate that a method doesn’t return a valueThe return statement must not specify a valueExample: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 statementReach the closing brace of the method16Sending messages to objectsWe don’t perform operations on objects, we “talk” to themThis is called sending a message to the objectA 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 jobExamples: 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 structureA program consists of one or more classesTypically, each class is in a separate .java fileProgramFileFileFileFileClassVariablesConstructorsMethodsVariablesVariablesStatementsStatements20nullIf 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, withjohn = new Person();String name = “John Smith";...then the value of the variable is nullnull is a legal value, but there isn’t much you can do with


View Full Document

Penn CIT 591 - Class Structure

Documents in this Course
Stacks

Stacks

11 pages

Arrays

Arrays

30 pages

Arrays

Arrays

29 pages

Applets

Applets

24 pages

Style

Style

33 pages

JUnit

JUnit

23 pages

Java

Java

32 pages

Access

Access

18 pages

Methods

Methods

29 pages

Arrays

Arrays

32 pages

Methods

Methods

9 pages

Methods

Methods

29 pages

Vectors

Vectors

14 pages

Eclipse

Eclipse

23 pages

Vectors

Vectors

14 pages

Recursion

Recursion

24 pages

Animation

Animation

18 pages

Animation

Animation

18 pages

Static

Static

12 pages

Eclipse

Eclipse

23 pages

JAVA

JAVA

24 pages

Arrays

Arrays

29 pages

Animation

Animation

18 pages

Numbers

Numbers

21 pages

JUnit

JUnit

23 pages

Access

Access

18 pages

Applets

Applets

24 pages

Methods

Methods

30 pages

Buttons

Buttons

20 pages

Java

Java

31 pages

Style

Style

28 pages

Style

Style

28 pages

Load more
Download Class Structure
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Class Structure and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Class Structure 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?