classes and objects object-oriented basics. vocabulary review – c++ class object instance this new...

16
CLASSES AND OBJECTS CLASSES AND OBJECTS Object-Oriented Basics

Upload: bethany-newton

Post on 29-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

CLASSES AND OBJECTSCLASSES AND OBJECTSObject-Oriented Basics

Page 2: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Vocabulary Review – C++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

Page 3: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Object-Oriented ConceptObject-Oriented Concept ReviewReview

• 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?)

Page 4: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Simple ClassSimple Classpublic 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]; }

Page 5: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

ContinuedContinuedpublic 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]);

}

Page 6: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

ContinuedContinued//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();

}

}

Page 7: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Methods in JavaMethods 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?

Page 8: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

More Instance Method ExamplesMore Instance Method Examplespublic 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++

Page 9: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Static Method ExamplesStatic 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

Page 10: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

VariablesVariables

• Instance – each object has its own copy

• Class/static – one copy per class. Often used with final.

• Local – only exists inside the function

Page 11: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

BankAccount ExampleBankAccount 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

Jim50001

Sally100002

mine yours

Page 12: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

VariablesVariables

• 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++)

Page 13: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Instance vs Static vs Local – Which to Use?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

Page 14: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

Intance vs Local vs Static ExampleIntance 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

Page 15: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

DON’T DO THIS!!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);

}

}

Page 16: CLASSES AND OBJECTS Object-Oriented Basics. Vocabulary Review – C++ Class Object Instance this new Constructor Default constructor Access (private/public/protected)

DO SOMETHING LIKE THIS!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(););

}

}