Examples for this lesson:
Inheritance Example
************************************************************
Creating a reference vs. creating an object
References are created with: Date a;
Objects are created with: new Date();
An object can have multiple references
Date a = new Date();
Date b=a;
(This does not copy the object!)
The convention of object oriented programming
Objects provide black boxes that perform useful tasks
Objects should use Accessor and Mutator methods for all variables
Objects should contain only methods and data which is relevant
Terms:
Accessor, a method that gets an instance variable of an object:
public VariableType getMyVar();
Mutator, a method that alters an instance variable of an object
public void setMyVar( VariableType myVar )
Static Variables and Methods
Static Variables and Methods are only placed in memory once
When new objects are created all non-static methods are duplicated
To call static methods an instance of a class is not needed
Why is main static?
When the JVM executes main it does not create an object first.
Since there is no object, main must be static in order to be accessible
Access Modifiers (public and private)
private is used to limit the access to a variable or method
private methods and variables are only accessible within a class
public allows access to a method or variable from all other classes
Default access modifier
Allows for “public” like access from within the package only
Garbage Collection
In Java all un-referenced objects are regularly “cleaned up”
Garbage collection can not be called only suggested; System.gc()
When GC occurs, the JVM determines what to “clean up”
Inheritance (is-a):
Inheritance is an implementation of a natural state “is-a”
extends
the parent is called a “super” class
cannot access the parents private variables or methods
accesses parent functions using “super”
Access Modifier: protected
objects that extend a class may access this method or variable directly
polymorph ism: An instance of an inherited object can be referenced as both the inherited object type or the parent object type(because a square is-a rectangle)
instanceof operator
Every class extends Object
There are basic methods available with Object that should be overridden
equals()
toString()
Boxing and unboxing of primitives in 5.0
Java automatically handles type conversion between primitive and non-primitive types in 5.0. This is Called Boxing and un-boxing
Abstract Class
Defines an “Interface” for a class
Implements
Classes can “Implement” multiple Abstract classes.
Must implement all methods in the abstract class.
Final Class
Can not be extended.
Breaking Encapsulation
Methods should return copies of return objects
If a method returns a reference to a private object encapsulation is broken.
Cloning of Objects
Most Classes have their own methods for copying
Implementing Cloneable is one method for creating a copy method for a class.