Basics of OOP
•
•
•
•
•
Creating a project
Running a project
Debugging a project
Profiling a project
Adding libraries to a project
Page 2 4/1/2012
Write the .java file
Compile the file into a
.class file
Run the .class file
Page 3 4/1/2012
1.
package helloworld;
2.
public class HelloWorld{
3.
public static void main(String[] args) {
4.
System.out.println("Hello World!");
5.
}
6.
}
– Hello World !
– An entry point is the point from which the execution of the program starts.
– When running a Java application, a "main" method is searched for.
• If it does not exist, the application cannot be run.
• If multiple entry points exist, they can be managed with runtime configurations.
– Packages are ways of grouping classes and separating namespaces
– A namespace is the scope in which a type name is visible
– Compiling from the command line
• javac [program_name].java
– Running from the command line
• java [program_name].class
• java -jar [arhive_name].jar
– Java programs run in a Virtual Machine
– Leads to better design
– Groups related functions and variables in objects
– Facilitates code reuse
– Better abstraction
– A "universe centric" (i.e. model) approach as opposed to an "algorithm centric" approach
– A class is a template from which objects can be created.
– A class does not represent any particular object, but that which all objects have in common.
– There is only one definition of what a cat means, but there are multiple specific cats.
– An object is an "instance" of a class. While the class "Cat" represents the general definition of a cat, an object of the class represents a particular cat.
– Attributes are characteristics of an object such as size, name, color etc.
– An attribute is with by specifying a type and a name for the attribute
– Methods are actions which an object can take such as speaking, running etc.
– All objects of the same class can do the same set of actions (e.g. all cats can meow)
– Methods are basically functions associated with a particular class of objects
– Methods are declared by specifying a prototype (return type, a name for the method a list of parameters) and a method body (to be executed when a method is called)
– The "new" operator creates an instance
(an object) based on a class and calls its constructor.
– When creating and object the reference to the object has to be kept somewhere to be able to access it
– A variable can hold the reference to an object or a primitive data type value
– The constructor method of an object is a special member which is called automatically on its creation
– It is always public and has no return type
– The "this" keyword is the way an object refers to itself
– Since a method is the same for all objects in a class, it must know what object it is to be applied to, so a hidden reference to the current object is sent to all method calls
1.
2.
3.
4.
public Cat(int weight, String name) {
this.weight = weight;
this.name = name;
}
Page 18 4/1/2012
1.
2.
3.
4.
5.
package simpleclassesv2; public class Cat {
int weight;
String name;
public Cat(int weight, String name) {
this.weight = weight; 6.
7.
8.
this.name = name;
}
9.
public void meow(){
10.
System.out.println(this.name+" meows");
11.
}
12.
}
Page 19 4/1/2012
– In Java objects are not explicitly deallocated
– The garbage collection mechanisms deallocates objects which are not referred by other objects
– If special resources should be deallocated when the object is destroyed, the "finalize" method can be overridden
– If special resources should be deallocated when the object is destroyed, the "finalize" method can be overridden
– As the garbage collection time is not controllable, neither is the moment when the method is invoked
1.
protected void finalize() {
2.
//close open resources
3.
}
Page 22 4/1/2012
– Variables can hold references to objects as well as primitive types
– Variables are visible within the scope in which they are declared (i.e. a variable declared in a method is not accessible outside it)
– Java is statically typed so a variable must be declared before use:
• [type] [name];
Page 23 4/1/2012
1.
//a variable holding a reference
2.
Cat somecat = new Cat(“somecat”);
3.
//a variable holding a value
4.
int i = 0;
Page 24 4/1/2012
– Objects are accessed through references
– The default value of an object is "null" (no reference)
1.
//creating a Cat object and storing the address
2.
// in a reference
3.
Cat somecat = new Cat("somecat");
4.
//using the reference to access a method
5.
somecat.meow();
6.
//a different cat object with a
7.
//different address
8.
Cat someothercat = new Cat("someothercat");
9.
someothercat.meow();
10.
//somecat will be garbage collected at
11.
//some point
12.
somecat = null;
– Instance members are members of a class which can only make sense for a particular object (e.g. the name of a person)
– Both class and instance members can be methods and attributes
– Class members are members of a class which only make sense for the totality of the objects of the same class (e.g. the total number of cats)
• Class members are marked as static
• Static members have only one value
Page 28 4/1/2012
1.
public class Cat {
2.
//an instance variable
3.
private String name;
4.
//a class variable
5.
static int number = 0;
6.
//…
7.
//other properties and methods
8.
}
– Encapsulation means keeping the characteristics and the behavior to together (as well as restricting direct access to the characteristics)
– Inheritance means reusing the definition of an object by defining objects with derived behavior
– Polymorphism means determining the actual type of the object at runtime
– Accessing fields through functions restricts and controls possible misuse
– The visibility of fields and functions is affected through access modifiers
• Private fields cannot be accessed from outside the object
• Public fields are accessible from outside the object
– Access to private fields can be offered through getter and setter methods
1.
2.
3.
4.
5.
//…
//the property is now private private String name;
//a getter method is used to access its value public String getName() {
return name; 6.
7.
8.
}
//a setter method allow for possible validations
9.
public void setName(String name) {
10.
this.name = name;
11.
}
Page 32 4/1/2012
– Inheritance means deriving objects from other objects.
– The child object will inherit all the characteristics of the parent(both fields and methods)
• Inheritance is done through the "extends" keyword
1.
public class Bird {
2.
//…
3.
}
4.
public class Duck extends Bird{
5.
//…
6.
}
– The child object can extend or override the definition of the parent
• In order to override a method, the child class must specify a method with the same prototype
6.
7.
8.
1.
2.
3.
4.
5.
//method in the parent class
public void fly(int distance){
System.out.println("Flew " + distance);
}
//method in the child class
public void fly(int distance){
System.out.println(“Refused to fly”);
}
Page 36 4/1/2012
– If a method was overridden the parent method can still be accessed through the
"super" keyword
– "super" represents the parent class
Page 37 4/1/2012
1.
public class Duck extends Bird{
2.
public Duck(String name) {
3.
super(name);
4.
}
5.
}
Page 38 4/1/2012
– Java lacks multiple inheritance since it can lead to complex development problems
(i.e. diamond inheritance)
– Java does however support specifying multiple behaviors through the use of interfaces
– Interfaces only contain fields and method prototypes
• Interfaces are always public
• Method prototypes define the form of a method, but not its actual behavior
• Interfaces are "implemented" (by using the keyword "implements")
1.
package troublewithpenguins;
2.
public interface FlyingBehavior {
3.
public void fly(int distance);
4.
}
– Interfaces are "contracts" between the definer of an object and it user
– An implementer of an interface must implement all methods
1.
2.
3.
4.
5.
public class Bird implements FlyingBehavior{
//…
public void fly(int distance){
System.out.println(“flying”);
}
•
•
• Abstract classes are classes with unimplemented (abstract) methods
An abstract class cannot be instantiated
Abstract classes are extended, not implemented
Page 44 4/1/2012
6.
7.
8.
1.
2.
3.
4.
5.
abstract public class Bird {
//if a class has an abstract method
//it must itself be abstract
public abstract void swim(int distance);
public void fly(int distance){
System.out.println(“flying”)
}
}
Page 45 4/1/2012
– A final field cannot be changed
– A final method cannot be overridden
– A final class cannot be inherited
– Subclasses (child classes) inheriting a parent class can define their own behavior
(add or override methods)
– A reference to an object ca hold any compatible type(i.e. if Cat extends Animal), an Animal reference can hold a Cat because the Cat has at least the characteristics of an Animal
– While inheritance ("is-a") facilitates code reuse it is generally not flexible enough if changes occur
– Composition ("has-a") means having an object as a member of another object. This has the advantage of constructing complex objects from simple behaviors.
1.
//a duck is a bird
2.
public class Duck extends Bird{
3.
//…
4.
}
5.
//but
1.
//a car has a trunk
2.
public class Car{
3.
Trunk carTrunk;
4.
//…
5.
}
– Java supports both primitive types and reference types
• Primitive data types are value types (they hold an actual value)
• Objects are reference types (they hold a reference to the memory)
– Arrays contain a set of primitive values or object accessible through their position
– byte - 8 bit integer
– short - 16 bit integer
– int - 32 bit integer
– long - 64 bit integer
– float - 32 bit floating point number
– double - 64 bit floating point number
– boolean - true or false
– char - 16 bit UNICODE character
•
•
An enumerated type is a fixed list of constants
Java enums are, however, more flexible and have an associated class
Page 53 4/1/2012
•
•
•
•
//declare an enum public enum Day { SUNDAY, MONDAY,
TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY }
//declare a variable holding an enum
Day someday = Day.MONDAY;
Page 54 4/1/2012
– The String class represents a character string
– Strings are immutable
– Strings are created by enclosing text in double quotes ("“)
– Immutable types cannot be modified
– If a String is assigned a new value, the virtual machine creates a new String
– Arrays are container objects holding a determined number of elements
– System.arraycopy
– Collections
– Assignment operator
– Arithmetic operators
– Unary operators
– Equality operators
– Relational operators
– Conditional operators
– instanceof operator
– Bitwise and bitshift operators
– Cast operators
– expr ++ expr –
– ++ expr -expr + expr expr ~ !
– * / %
– + -
– << >> >>>
– < > <= >= instanceof
– == !=
– &
– ^
– |
– &&
– ||
– ? :
– = += -= *= /= %= &= ^= |= <<= >>= >>>=
– if/else
– switch
– For
– While
– Do..while
– For each
1.
if ((i%2) == 0){
2.
System.out.println("even");
3.
}
4.
else{
5.
System.out.println("odd");
6.
}
1.
switch(i){
2.
case 1:
3.
System.out.println("1");
4.
break;
5.
case 2:
6.
System.out.println(“2");
7.
break;
8.
default:
9.
System.out.println("x");
10.
break;
11.
}
1.
Byte[] bytes = {1,2,3,4,5};
2.
for (int j = 0; j < bytes.length; j++) {
3.
System.out.println(bytes[j]);
4.
}
1.
for (Byte item : bytes) {
2.
System.out.println(item.byteValue());
3.
}
1.
int i=5;
2.
while (i>0){
3.
i--;
4.
System.out.println(bytes[i]);
5.
}
1.
int i=5;
2.
do{
3.
i--;
4.
System.out.println(bytes[i]);
5.
}while(i>0);
– Javadoc
– Adding javadoc with netbeans
– Naming conventions
– Camel Case
– Javadoc allows you to add documentation within the code itself(the same code can be compiled to produce documentation)
– Frequent tags
• @author
• @version
• @param
• @return
• @exception
1.
/**
2.
*
3.
* @param subject
4.
* @return number of meows
5.
* @exception generic exception
6.
*/
7.
public int meow(String subject) throws
Exception {
8.
//some code
9.
return n;
10.
}