Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays and Objects OO basics. Topics Basic array syntax/use OO Vocabulary review Simple OO example Instance and Static methods Static vs. instance vs.

Similar presentations


Presentation on theme: "Arrays and Objects OO basics. Topics Basic array syntax/use OO Vocabulary review Simple OO example Instance and Static methods Static vs. instance vs."— Presentation transcript:

1 Arrays and Objects OO basics

2 Topics Basic array syntax/use OO Vocabulary review Simple OO example Instance and Static methods Static vs. instance vs. local A few exceptions (array, null ptr)

3 ARRAYS Collections of Data

4 Array Basics Similar to C++, but always allocated: double [] data = new double[10]; Can also have arrays of objects: BankAccount[] accounts = new BankAccount[MAX]; Access is similar to C++, but if code goes beyond array bounds an exception is thrown: for (int i=0; i<=10; ++i) System.out.println(data[i]); // ArrayIndexOutOfBoundsException on data[10] Arrays have built-in field named length for (int i=0; i < data.length; ++i) System.out.println(data[i]);

5 Array Initialization Common to forget to allocate space double[] data; data[0] = 29.5; Can initialize in declaration, like C++: int[] primes = {2, 3, 5, 7, 11}; Can use an anonymous array as parameter: new int[] {2, 3, 5, 7, 11}

6 CLASSES AND OBJECTS Object-Oriented Basics

7 Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected) static parent/child; superclass/subclass abstract class/pure virtual function

8 Object-Oriented ConceptReview Encapsulation – hiding unimportant details Black box – something that magically “does its thing” Abstraction – taking away inessential features Example: car –if engine control module fails, replace it –mechanic can provide inputs, test outputs –doesn’t need to know how it works OO challenge: finding the right abstractions (what “black boxes” do we need to solve the problem at hand?)

9 Simple Class public class Book { // static = one copy per class // final = constant, can't change public static final int MAX_HIGHLIGHTS = 100; // these are INSTANCE variables // may also be called ATTRIBUTES or MEMBER variables // In CSCI306, MUST be private unless you have a compelling argument otherwise private int numPages; private int[] highlights; private int numHighlights; private int currentPage; public Book(int numPages) { super(); // covered in more detail under Inheritance this.numPages = numPages; currentPage = 1; // Notice use of constant, avoid 'Magic constants' // highlights = new int[100]; - NOT GOOD!!!!! highlights = new int[MAX_HIGHLIGHTS]; }

10 Continued public void addHighlight() { highlights[numHighlights] = currentPage; numHighlights++; } public void addHighlight(int whichPage) { highlights[numHighlights] = whichPage; numHighlights++; } public void printHighlights() { System.out.println("Highlighted pages\n"); for (int page=0; page<numHighlights; page++) System.out.println(highlights[page]); }

11 Continued //Setters and getters by Eclipse public static void main(String[] args) { Book aBook = new Book(300); aBook.setCurrentPage(15); aBook.addHighlight(); aBook.addHighlight(32); aBook.printHighlights(); }

12 Methods in Java Instance –called with an object –most methods are of this type –able to access/update object (instance) data Class/static – called with the class name –also known as static –no object, so no object data… must pass needed data in as parameters –don’t make a static method unless you have a reason –main is static – why?

13 More Instance Method Examples public class MyPoint { private int x, y; public MyPoint(int x, int y){ this.x = x; this.y = y; } public int getX() { return x; } } // in main MyPoint p1 = new MyPoint(3, 4); MyPoint p2 = new MyPoint(5, 6); System.out.println(p1.getX()); System.out.println(p2.getX()); notice that you call an instance method using an object constructor – just like C++

14 Static Method Examples Existing class: System.out.println(Math.round(x + y)); Example of creating your own: public class Financial { public static double percentOf(double p, double a) { return (p/100) * a; } double tax = Financial.percentOf(taxRate, total); Call with class name, not instance. NOTE: inside class, don’t need class name All data is passed in, no “owned” variables numerous Math functions static keyword

15 Variables Instance – each object has its own copy Class/static – one copy per class. Often used with final. Local – only exists inside the function

16 BankAccount Example lastAccountNum public class BankAccount { private static int lastAccountNum = 0; private String name; private double balance; private int accountNum; // methods here } BankAccount mine = new BankAccount(“Jim”, 5000); BankAccount yours = new BankAccount(“Sally”, 10000); just one copy of lastAccountNum Jim 5000 1 Sally 10000 2 mineyours

17 Variables Instance variables –each object has its own copy (as in C++) –objects are automatically garbage collected (unlike C++!) –fields are initialized with a default value (e.g., 0, null) if not explicitly set in constructor. Still good to do your own initialization. –NullPointerException if you forget to call new Local variables –must be explicitly initialized –error if you use before initializing (unlike C++) –only exist inside method (as in C++)

18 Instance vs Static vs Local – Which to Use? Use instance variables for data that “belong” to one instance of the class and will be operated on by multiple methods Use local variables for temporary calculations within a method Use static variables ONLY for constants and values that are clearly shared between objects. If you don’t have a reason for static, don’t use it! Use static methods for utility methods Common mistake – use static just to get rid of compiler errors

19 Intance vs Local vs Static Example public class Financial{ public static double percentOf(double p, double a) { return (p/100) * a; } public class BankAccount { private double balance; private double intRate; // addInterest updates balance & returns amt of interest public double addInterest() { double interest = balance * intRate; balance += interest; return interest; } Common errors: Making all variables instance, even if only used in one function. Making all variables static – like using globals! instance variables, can access inside all instance methods local variable: interest

20 DON’T DO THIS!! public class SomeClass { public static int count; public static void update() { count++; } public static void main(String[] args) { count = 0; //.. Some stuff update(); //.. Some stuff update(); System.out.println(count); }

21 DO SOMETHING LIKE THIS! public class SomeClass { private int count; // let Eclipse do getter/setter public void update() { count++; } public static void main(String[] args) { SomeClass sc = new SomeClass(); // not needed, done in constructor: count = 0; //.. Some stuff sc.update(); //.. Some stuff sc.update(); //System.out.println(count); System.out.println(sc.getCount();); }


Download ppt "Arrays and Objects OO basics. Topics Basic array syntax/use OO Vocabulary review Simple OO example Instance and Static methods Static vs. instance vs."

Similar presentations


Ads by Google