CSH 2009-2010 Intro. to Java The Big Ideas in Computer Science • • • • • Beyond programming Solving tough problems Creating extensible solutions Teams of “Computational Thinkers” Encapsulation & Abstraction Why Java • Portable and Safe • Created in 1991 by James Gosling & Patrick Naughton of Sun Microsystems to run on devices • Enter the web! • Full fledge programming language like C++ only simpler (nothing in common with JavaScript) • Object Oriented – represents best thinking in CS • Vast libraries of classes you can use • Now there is an enterprise and a mobile version Schematic Diagram of a Computer Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Central Processing Unit Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. A Hard Disk A Motherboard The ENIAC Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Why Java: the JVM • Java Virtual Machine • CPU created in software layered on top of the Operating System • Strong security limits access outside the JVM (safe) • Programs compiled for the JVM run on all platforms WITHOUT modification; this is not true for other languages. Write once – run anywhere! Java: some basics • Primitive data types: int, double, boolean • Any variable you use in program must have a data type. • Data type of a variable is declared (announced) the first time you use the variable. • String is not a primitive data type; it is what is called an object data type. Data Types and Variables • an int stands for integer which means number without decimal parts (whole number) • a float stands for floating point or decimal number • a double is poorly named and stands for double precision decimal. Doubles can have twice as many decimal places as a float. • a boolean is either TRUE or FALSE • a String is a sequence of characters Data Types and Variables int x = 3; //declares an int variable x and sets it to hold 3 x = 7; //sets x to hold 7 replacing the 3 System.out.println(x); //prints out 7 double price = 8.25 //declares a double variable price and sets it // to hold 8.25 price = price + 1.0; //add 1.0 to what is held in price System.out.println(price); //prints out 9.25 boolean isOpen = TRUE; //declares a boolean variable isOpen and //sets it to hold TRUE isOpen = FALSE; //replaces TRUE with FALSE in isOpen if(isOpen) //does not print since isOpen holds FALSE System.out.println(“The lock is open.”); Some Java Syntax (just a little bit) Code statements end with a semicolon Pairs of curly braces are used to organize code in to blocks in Java { statement; statement; statement; } Blocks can be nested { statement; { statement; } } Vocabulary of Object Oriented Programming Class: a blueprint for making one or more objects; an object “factory” Object: created in memory using the constructor in a class according to the blueprint Square Class….makes….. Square Objects Looking at the Blueprint Every class has 3 parts to it that you should come to know and love: Fields: what an object of this class will be able to store inside its “brain” Constructors: when activated these create objects from the blueprint Methods: what an object of this class will be able to do once created Vocabulary of Object Oriented Programming Access Level: Private: only accessible “inside” the object; not available to “outsiders” such as other objects (fields are usually private) Public: accessible any outside object (constructors are always public and methods are usually public) /** This class represents a BankAccount */ public class BankAccount { } /** This class represents a BankAccount */ public class BankAccount { /** fields */ private double balance; } /** This class represents a BankAccount */ public class BankAccount { /** fields */ private double balance; /** constructors */ public BankAccount() { balance = 0.0; } public BankAccount(double b) { balance = b; } } /** This class represents a BankAccount */ public class BankAccount { /** fields */ private double balance; /** constructors */ public BankAccount() { balance = 0.0; } public BankAccount(double b) { balance = b; } public double getBalance() { return balance; } public void deposit(double howmuch) { balance += howmuch; } public void withdraw(double howmuch) { balance -= howmuch; } public void printBalance() { System.out.println("Balance:” + balance); } } Looking Closer at Fields • All variables must be declared (announced) BEFORE they can be used to hold a value. • Instance fields are variables that are like properties in Alice. They belong to a class of objects. They are stored in memory – in the object’s “brain.” • Fields are usually private and are declared at the top of a class. private double balance; access return type name of variable Looking Closer at Methods • Methods are usually public but sometimes can be private. Private methods can only be used inside other methods of the same class. Public methods can be called by objects of other classes. • Methods must have a return type which indicates what type of information they give back when called (i.e. int, double, String). If a method does not give back anything than it its return type is void. In Alice a method which returned something was known as a function. • The top line of a method is called its signature. public void deposit(double howmuch) { balance += howmuch; } Looking Closer at Methods • Method signatures contain access level, return type, name of method, and any method parameters. • The body of the method is the part in { }. The body for the method contains code to actually do (implement) what the method was designed to do. • Methods which return the information in a object’s private fields are called accessors. • Methods which modify and object’s private fields in their body are called mutators. return type of parameter name of parameter public void deposit(double howmuch) { balance += howmuch; access } return type name of method public double getBalance() { return balance; } public void deposit(double howmuch) { balance += howmuch; } public void withdraw(double howmuch) { balance -= howmuch; } public void printBalance() { System.out.println("Balance: " + balance); } } Accessor Mutator Mutator Neither Looking Inside objects Objects store values inside them. These values are stored in variables called instance fields(brain slots). Fields are private and are not accessible outside of the object. Only the object knows what is in its fields. The current values of fields in a given object are called its state. ONLY IN BLUEJ CAN WE LOOK DIRECTLY INSIDE OBJECTS. Looking Inside objects NORMALY IN JAVA, TO GET INFORMATION INSIDE OBJECTS YOU MUST GO THRU THE OBEJCTS METHODS. The values in an object’s fields can only be accessed indirectly through the use of public methods. These methods are called accessors. The values in an object’s fields can only be changed indirectly through the use of a public method. These methods are called mutators. i.e. barronAccount.getBalance(); barronAccount.deposit(10000); Practice with a class • Practice with the BankAccount class as follows: ▫ For practice with the compiler type it in off your sheet. ▫ FIRST just type in the constructors, compile and try it out by making some BankAccount objects and looking inside them. ▫ THEN add the methods ONE at a time. Compile and test each by making an object. Classes that are already part of Java • The Java API lists all the classes that are part of Java. • For each class, it lists the constructors and all of the methods. • http://java.sun.com/javase/6/docs/api/ Creating Objects WITHOUT BlueJ public class TestBankAccount { //test class for the BankAccount class public static void main(String args[]) { BankAccount b1t = new BankAccount(100); b1.deposit(100); b1.withdraw(100); b1.printSlip(); } } //main method A Look Inside Memory • Java protects you from having to worry about memory very much • Objects exists at certain memory locations once created • Objects names are really called object references and they refer to a memory location MrBAccount b1 @667fd3 @197bb7 Memory Creating Objects The correct way to create objects is by “invoking” the constructor as follows: Refer to a class and say “new Square with length 5” in Java this would be new Square(5); Constructors are always named the same as the class. Constructors must be public or else objects would never be able to be created from their blueprints (classes) Creating & Interacting with Objects The correct way to create and interact with objects is through their constructors and methods is as follows: Create an object an object and name it (give it a reference). Square happySquare = new Square(50); Send a message to an object and say “happySquare dot changeColor to blue” in Java this would be happySquare.changeColor(blue); Aside on Parameters (inputs) • Public variables which act as inputs and which pass their values into a method or constructor where they can be used. Parameters cannot be used outside of the method they are declared in. Recall functions from algebra f(p,q) • i.e. consider a method public int sum(int a, int b) { int s = a + b; return s; } Practice More • Complete the Employee class compiling & testing thoroughly in BlueJ. • Create TestEmployee test class in BlueJ compiling and running main method.