Download Y - ssucet.org

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
3. MORE OOP IN JAVA
REFERENCE:
HTTP://DOCS.ORACLE.COM/JAVASE/TUTORIAL/JAVA/JAVAOO/ACCESSCONTROL.HTML
INSTANCE VS. STATIC MEMBERS
public class Foo
{
private int x;
private float y;
private static int count = 0;
// Instance attribute
// Instance attribute
// Static attribute
public Foo(int a, float b)
// Instance constructor
{
x = a;
// ... modifying instance attribute
y = b;
// ... modifying instance attribute
count++;
// ... modifying static attribute
}
public float total()
{
return x + y;
// Instance method
}
public static int getCount()
{
return count;
}
// Static method
public static void main(String[] args) // Static method
{
Foo i = new Foo(4, 7.3f);
// Making a new instance i
Foo j = new Foo(3, 9.2f);
// Making a new instance j
System.out.println("i's total = " + i.total());
System.out.println("j's total = " + j.total());
System.out.println("count = " + getCount());
}
}
• [Point out differences, define instance / static
member]
PACKAGES
• A package is a grouping mechanism.
• prevents name collisions
• A good organizational tool
• In the JDK, for example, we've done this:
import java.util.Scanner;
// …
Scanner new = new Scanner(System.in);
• In some .java file, there was something like this:
package java.util;
class Scanner { /* Lots of "stuff" */ }
• Side note1: The java.util package has a lot of classes. If
you want to have access to them all, you can use:
import java.util.*;
• Side note2: Instead of importing (or if there is ambiguity),
you can do this as well:
java.util.Scanner = new java.util.Scanner(System.in);
• [Discuss use in making our own "modules"]
NESTED CLASSES
• Basically a class within a class.
• Why?
• Organization / Readability: we don't have to look in 2+ files.
• Encapsulation: We can hide the nested class from users of
the outer class (if we choose)
package nestedexample;
public class Outer
{
private class Inner
{
private float y;
Inner(float b)
{
y = b;
}
public String blah()
{
return "Bl_" + y + "_ah";
}
}
private Inner x;
public Outer(float c)
{
x = new Inner(c);
}
public void test()
{
System.out.println("Te_" + x.blah() + "_st");
}
public static void main(String[] args)
{
Outer o = new Outer(3.2f);
o.test();
}
}
NESTED
CLASS
EXAMPLE
PUBLIC / PRIVATE / PROTECTED
• A way to control who can access parts of the class
• Why?
•
•
•
•
Good Design*
A way to "bullet-proof" your code.
Can make it easier to modify your code.
Jason says so 
• It'll be a bit aggravating at first…
• Basic idea:
• Put a modifier in front of a "thing"
•
•
•
•
An attribute (variable)
A method (function)
A nested class
…
• 4 modifiers: public, private, protected, [no modifier = packageprivate].
• 4 contexts: in-class, in-package, in-subclass, world
CONTEXT EXAMPLES
// TheClass.java
package accessexample;
// OtherClass.java
package accessexample;
public class TheClass
{
public class OtherClass
{
In-class
Inpackage
}
import accessexample.*;
public class TestApp
{
public static void main(String[] args)
{
World
}
}
}
// OtherClass.java
import accessexample.TheClass;
public class OtherClass extends TheClass
{
In-subclass
}
This is the class of interest
ACCESS RULES
Can access?
Modifier
In-class
In-package
In-Subclass
World
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier (packageprivate)
Y
Y
N
N
private
Y
N
N
N
• [Do some examples within the classes on the last
slide]
INHERITANCE
• Main idea:
• Create a new class (Child) from an existing
one (Parent)
• Add new methods to the Child class
[optional]
• Re-implement methods from the Parent
class [optional]
• Advantages:
• Don't have to re-type old code
• And changes to Parent automatically
propogate
• Natural type-description
• If "Apple" is a type of "Fruit", use inheritance.
• Used extensively in Java
BASIC EXAMPLE
public class Shape
{
protected Color mColor;
public Shape(Color c) { mColor = c; }
public Color getColor () {return mColor; }
}
public class Circle extends Shape
{
protected float mRad;
public Circle(Color c, floar r) { super(mColor); mRad = r; }
public float getRadius() { return mRad; }
}
public class Box extends Shape
{
protected float mWidth, mHeight;
public Box(Color c, floar w, float h) { super(mColor);
mWidth = w; mHeight = h; }
public float getWidth() { return mWidth; }
}
BASIC EXAMPLE, CONT.
public static void main(String[] args)
{
Shape s = new Shape(Color.RED);
Circle c = new Circle(new Color(255,255,0), 5.0f);
Box b = new Box(Color.BLUE, 20.0f, 13.0f);
System.out.println(s.getColor()); // Java AWT Color(r=255,g=0,b=0)
System.out.println(c.getColor()); // Java AWT Color(r=255,g=255,b=0)
System.out.println(c.getRadius()); // 5.0
//System.out.println(b.getRadius());
// ERROR!
//System.out.println(s.getRadius());
// ERROR!
System.out.println(b.getWidth()); // 20.0
}
IMPLEMENTS VS. EXTENDS
• Java only supports single-inheritance
• i.e. We can only extend from one class.
• However, a class can implement from any number
of interface classes
• Interface classes:
• Can't have attributes
• The methods have no bodies.
• Any class that implements an interface
• "Agrees" to implement all the methods.
• Can be passed as an argument to a function that expects an
instance of the interface class.
public interface Drawable
{
public void draw();
}
IMPLEMENTS
EXAMPLE
public interface Moveable
{
public void moveTo(int x, int y);
}
class Box extends Shape implements Drawable, Moveable
{
protected float mWidth, mHeight;
protected int mX, mY;
public Box(Color c, floar w, float h) { super(mColor);
mWidth = w; mHeight = h; }
public float getWidth() { return mWidth; }
public void draw() { /* … */ }
public void moveTo(int x, int y) { mX = x; mY = y; }
}
// elsewhere…
void foo(Drawable d)
{ d.draw(); }
// …elsewhere
Box b = new Box(Color.BLUE, 32.0, 15.0);
foo(b);
OBSERVER / LISTENER
DESIGN PATTERN
• A good example of Inheritance
• Especially the implements aspect
• When writing a program, there are many times
when your program is waiting for something.
• Some examples of waiting in a program:
• Waiting for the user to press a button.
• Waiting for a file to finish loading
• Waiting for a piece of data from the network.
http://www.reddit.com/r/pics/comments/186m5h/eyeball_guy_oc/
OBSERVER (NAÏVE APPROACH)
setup();
Boolean event_happened = False;
while (!event_happened)
{
// Do something to eat up CPU cycles.
Thread.sleep(4000);
// 4 seconds
}
do_the_work();
• Bad. Why?
• Reason#1: We could potentially do something useful.
• Reason#2: Infinite loop (see why?)
OBSERVER (BETTER APPROACH)
setup();
while (True)
{
updateNetwork();
int result = checkForButtonPresses();
if (result == 42)
do_the_work();
// etc.
if (…)
break;
}
• For this to work, each "helper function" must be nonblocking [define]
• This is an example of an asynchronous program loop.
• This works great if we have complete control over the
program.
• In Swing applications, Swing contains a loop like this. We
can't access it!
OBSERVERS
• Observers notify any "attached" Listeners when an
event occurs
• Often passing along extra info.
• The idea is pretty simple, but is used a lot in Java.
• [Do an example on computer]
• You’ll see this in action with Swing (Lab03)