programming with java

41
Programming with Java COP 2800 Lake Sumter State College Mark Wilson, Instructor

Upload: prema

Post on 22-Feb-2016

43 views

Category:

Documents


0 download

DESCRIPTION

Programming with Java . COP 2800 Lake Sumter State College Mark Wilson, Instructor. Programming with Java. Vocabulary. Java Terms. ž Accessor žAPI žArgument žArray žByte žCasting žClass žCompiler žConditional žConstant. žDebug žDouble žEncapsulation žExpression žField žFloat - PowerPoint PPT Presentation

TRANSCRIPT

Programming with Java

Programming with Java COP 2800Lake Sumter State College

Mark Wilson, InstructorProgramming with JavaVocabularyJava TermsAccessorAPIArgumentArrayByteCastingClassCompilerConditionalConstantDebugDoubleEncapsulationExpressionFieldFloatInheritanceInstance VariableIntegerInterpreterMore Java TermsJDKJVMLocal VariableLoopMemberMethodMutatorObjectOperatorOverrideParameterPolymorphismPrivatePublicStatementStaticStringStructured ConstructThisTypeOur world consists of objects (people, trees, cars, cities, airline reservations, etc.).

Objects can perform actions which affect themselves and other objects in the world.

Object-oriented programming (OOP) treats a program as a collection of objects that interact by means of actions.

Object-Oriented ProgrammingObjects, appropriately, are called objects.

Actions are called methods.

Objects of the same kind have the same type and belong to the same class.Objects within a class have a common set of methods and the same kinds of databut each object can have its own data values.

OOP TerminologyOOP adheres to three primary design principles:EncapsulationPolymorphismInheritance

OOP Design Principlespacking things up, only seeing part of what is going on

Encapsulation provides a means of using the class, but it omits the details of how the class works.

Encapsulation often is called information hiding.

Encapsulation (Information Hiding)Michele Weigle - COMP 14 - Spr 048spreadAn automobile consists of several parts and pieces and is capable of doing many useful things.Awareness of the accelerator pedal, the brake pedal, and the steering wheel is important to the driver.Awareness of the fuel injectors, the automatic braking control system, and the power steering pump is not important to the driver.

Accessibility Exampleway of organizing classes. At each level classification becomes more specialized.Inheritance

Michele Weigle - COMP 14 - Spr 0410Classes can be organized using inheritance.

A class at lower levels inherits all the characteristics of classes above it in the hierarchy.

At each level, classifications become more specialized by adding other characteristics.

Higher classes are more inclusive; lower classes are less inclusive.

Introduction to Inheritancemany forms Same instruction to mean same thing in different contexts. Example: Go play your favorite sport. Id go play lacrosse.Others of you would play baseball instead.In programming, this means that the same method name can cause different actions depending on what object it is applied to.More on this in Chapter 8.

Polymorphism Michele Weigle - COMP 14 - Spr 0412openA set of instructions for solving a problem

By designing methods, programmers provide actions for objects to perform.

An algorithm describes a means of performing an action.

Once an algorithm is defined, expressing it in Java (or in another programming language) usually is easy.AlgorithmMichele Weigle - COMP 14 - Spr 0413Get out paper - write down how to make a PB&J sandwich

You just wrote an algorithmWrite better one on boardcombination of code and English used to express an algorithm before writing algorithm into code

PseudocodeMichele Weigle - COMP 14 - Spr 0414Write algorithm in pseudocodePBJS AlgorithmGet slice of bread from loaf and put on plateRepeat until enough peanut butterPut knife into peanut butter jar and get peanut butterTransfer peanut butter from knife to slice of breadTransfer other slice of bread from loaf to plateRepeat until enough jellyPut knife into jelly jar and get jellyTransfer jelly from knife to other slice of breadPut slice of bread (pb side down) on other slice of breadEnjoy!PBJS Algorithm RevisitedGet slice of bread Apply peanut butter Get other slice of breadApply jellyPut slice of bread (pb side down) on other slice of breadEnjoy!

Apply condimentPut knife into condiment jar and get condimentTransfer condiment from knife to slice of bread

Get breadGet slice of bread from loafPut on plate

Calling methods from methodsA method body can call another methodDone the same way:receiving_object.method();If calling a method in the same class, do not need receiving_object:method();Alternatively, use the this keywordthis.method();ThisReference to the current object the object whose method or constructor is being calledWithin a class definition, this is a name for the receiving objectthis.agethis.majorthis.getAge()Used when a field is shadowed local variable with the same name as an instance variableUsed for explicit constructors (more later)Frequently omitted, but understood to be therePublic Modifierpublic void setMajor()public int classYear;

public: there is no restriction on how you can use the method or instance variablePrivate Modifierprivate void setMajor()private int classYear;

private: can not directly use the method or instance variables name outside the classMore about PrivateHides instance variables and methods inside the class/object. The private variables and methods are still there, holding data for the object.Invisible to external users of the classUsers cannot access private class members directlyInformation hidingPrivate Instance VariablesForce users of the class to access instance variables only through methodsGives you control of how programmers use your classWhy is this important?public class Rectangle{ public int width; public int height; public int area;

public void setDimensions( int newWidth, int newHeight) { width = newWidth; height = newHeight; area = width * height; }

public int getArea() { return area; }}Example: RectangleRectangle box = new Rectangle();box.setDimensions(10, 5);System.out.println(box.getArea());

// Output: 50

box.width = 6;System.out.println(box.getArea());

// Output: 50, but wrong answer!Accessors and MutatorsHow do you access private instance variables?Accessor methods (a.k.a. get methods, getters)Allow you to look at data in private instance variablesMutator methods (a.k.a. set methods, setters)Allow you to change data in private instance variablespublic class Student{ private String name; private int age;

public void setName(String studentName) { name = studentName; }

public void setAge(int studentAge) { age = studentAge; }

public String getName() { return name; }

public int getAge() { return age; }}Example: StudentAccessorsMutatorsPrivate MethodsHelper methods that will only be used from inside a class should be privateExternal users have no need to call these methods

EncapsulationAccelerate with the accelerator pedalDecelerate with the brake pedalSteer with the steering wheelDoes not matter if:You are driving a gasoline engine car or a hybrid engine carYou have a 4-cylinder engine or a 6-cylinder engineYou still drive the same wayExample: driving a carThe interface is the sameThe underlying implementation may be differentEncapsulationEncapsulation in ClassesA class interface tells programmers all they need to know to use the class in a programThe implementation of a class consists of the private elements of the class definitionprivate instance variables and constantsprivate methodsbodies of public methodsExample: Rectanglepublic class Rectangle{ private int width; private int height;

public void setDimensions( int newWidth, int newHeight) { width = newWidth; height = newHeight; }

public int getArea() { return width * height; }}public class Rectangle{ private int width; private int height; private int area;

public void setDimensions( int newWidth, int newHeight) { width = newWidth; height = newHeight; area = width * height; }

public int getArea() { return area; }}

Implementation should not affect behavior described by interfaceTwo classes can have the same behavior but different implementationsEncapsulationGuidelinesInstance variables are privateProvide public accessor and mutator methodsMake helping methods privateMichele Weigle - COMP 14 - Spr 0432You are expected to follow these guidelines from now on.Global vs. LocalVariables are local to methodsInstance variables are Global for all methods in a class Public instance variables are Global for everyoneMichele Weigle - COMP 14 - Spr 0433Selective AmnesiaProgram a memory game involving of a sequence of random numbers between 1 and 10, inclusive, that are called out one at a time. Each player can remember up to 5 previous numbers. When the called number is in a player's memory, that player is awarded a point. If it's not, the player adds the called number to his memory, removing another number if his memory is full.

Both players start with empty memories. Both players always add new missed numbers to their memory but use a different strategy in deciding which number to remove:One player strategy is to remove the number that hasn't been called in the longest time.The other player strategy is to remove the number that's been in the memory the longest time.

Selective Amnesia ExampleTurnCalledNumberPlayer OneMemoryPlayer OneScorePlayer TwoMemoryPlayer TwoScore111010221,201,20341,2,401,2,40461,2,4,601,2,4,60511,2,4,611,2,4,61681,2,4,6,811,2,4,6,817101,4,6,8,1012,4,6,8,101821,2,6,8,1012,4,6,8,102941,2,4,8,1012,4,6,8,1031011,2,4,8,1021,4,6,8,103Programming with JavaLogicTruth TablePTFPQTTTFFTFFPQRTTTTTFTFTTFFFTTFTFFFTFFFUsing Truth TablesPPTFFTresult = p && q;result = p|| q;PQP QP QTTTTTFFTFTFTFFFFresult = !p;More TruthPQRP Q(P Q) RTTTTTTTFTTTFTFTTFFFFFTTFTFTFFFFFTFTFFFFFresult = (p && q) || r;result = p && q || r;Inclusive and Exclusive ORPQP QP QTTFTTFTTFTTTFFFFBitwisebyte a;11110000byte b;10101010byte (a ^ b);01011010Exclusive ORbyte a;11110000byte b;10101010byte (a | b);11111010Inclusive ORbyte a;11110000byte b;10101010byte (a & b);10100000AND