Java: Week 6
Java: Week 6
Abstraction
Before abstraction: Porche, Pinto, Semi, Motorcycle After abstraction: Vehicle
Encapsulation
All vehicles have: number of wheels, color, start(), accelerate(), decelerate(), turnOff()
Inheritance Polymorphism
Method Overloading
start(Key key) start (Screwdriver s, Hammer, h) The list of input variables must be unique for each overloaded method
Method Overriding
For vehicle: start() { engineStatus = ON } For bicycle: start() { throw new DoesNotStartEx()}
Access Specifiers/Modifiers
Private, Protected, Public, (none) Accessed By this class only All Package Inherited? No
Yes
Yes Yes
If your method returns nothing (void), you can use return alone.
return; Note: only use this when you want to exit the method early. No need to put it at the end!
Constructors
No return type If a class does not have a constructor defined, the compiler automatically adds a default constructor with no input values. Constructors are NOT inherited!
If you wish to inherit a constructor, you must write out the signature and call the parents constructor using the super keyword
Variable Scope
{} define the scope of a variable When using catch, for, and while, remember that items declared within the catch, for, or while are only in scope within the following {}
{
Try { //ex out of scope} Catch (Exception ex) {// ex in scope} Finally { // ex out of scope }
The stack
Once popped from the stack, the variables are out of scope
Garbage Collection
Cleans the heap Done sporadically by JRE after an object is out of the scope of the stack finalize() method of an object is called before the memory occupied by that object is released System.gc() makes a request that garbage collection take place, but there is no guarantee that it will happen Setting reference variables to null marks the associated object for garbage collection
Use the return value: Dog dog = Kennel.getDog() Use it directly: Kennel.getDog().speak(); Disregard it: Kennel.getDog()
-classpath parameter
When compiling and running classes that use other classes, the compiler and JRE need to know the location of the binaries of the classes in your import clauses.
javac -classpath . MyClass.java java -classpath . MyClass
When using multiple packages, you must do it from the root root by package Javac classpath mypackage/* *.java Java classpath mypackage/* ClsName
http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html