Upload
bethany-newton
View
215
Download
0
Embed Size (px)
Citation preview
CLASSES AND OBJECTSCLASSES AND OBJECTSObject-Oriented Basics
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
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?)
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]; }
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]);
}
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();
}
}
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?
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++
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
VariablesVariables
• Instance – each object has its own copy
• Class/static – one copy per class. Often used with final.
• Local – only exists inside the function
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
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++)
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
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
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);
}
}
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(););
}
}