Java Fundamentals

advertisement

Java Fundamentals

Basics of OOP

Using the Eclipse IDE

Creating a project

Running a project

Debugging a project

Profiling a project

Adding libraries to a project

Page 2 4/1/2012

How to write a Java program

Write the .java file

Compile the file into a

.class file

Run the .class file

Page 3 4/1/2012

A Simple Java Program

1.

package helloworld;

2.

public class HelloWorld{

3.

public static void main(String[] args) {

4.

System.out.println("Hello World!");

5.

}

6.

}

A Simple Java Program

– 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.

A Simple Java Program

– Packages are ways of grouping classes and separating namespaces

– A namespace is the scope in which a type name is visible

Exploring Java

– 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

Object Oriented Programming

Why OOP?

– 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

Classes and objects

– 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.

Classes and objects

– 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.

Object members

– 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

Object members

– 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

Object members

– 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)

Creating objects

– 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

Object constructors

– 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

– 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

Constructor example

1.

2.

3.

4.

public Cat(int weight, String name) {

this.weight = weight;

this.name = name;

}

Page 18 4/1/2012

Object example

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

Destroying objects

– 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

Object finalization

– 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

Custom finalization

1.

protected void finalize() {

2.

//close open resources

3.

}

Page 22 4/1/2012

Variables

– 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

Variables

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

Using objects

– Objects are accessed through references

– The default value of an object is "null" (no reference)

Using objects

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;

Class members and instance members

– 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

– 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

Class members and instance members

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.

}

The three pillars of OOP

– 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

Encapsulation

– 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

Controlling the access to a field

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

– 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

A class inheriting another

1.

public class Bird {

2.

//…

3.

}

4.

public class Duck extends Bird{

5.

//…

6.

}

Overriding methods

– 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

Overriding methods

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

The “super” keyword

– 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

Using the parent constructor

1.

public class Duck extends Bird{

2.

public Duck(String name) {

3.

super(name);

4.

}

5.

}

Page 38 4/1/2012

Simple vs Multiple Inheritance

– 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

– 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")

An example interface

1.

package troublewithpenguins;

2.

public interface FlyingBehavior {

3.

public void fly(int distance);

4.

}

Interfaces

– Interfaces are "contracts" between the definer of an object and it user

– An implementer of an interface must implement all methods

Implementing methods

1.

2.

3.

4.

5.

public class Bird implements FlyingBehavior{

//…

public void fly(int distance){

System.out.println(“flying”);

}

Abstract classes

• 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

Abstract classes

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

The "final" keyword

– A final field cannot be changed

– A final method cannot be overridden

– A final class cannot be inherited

Polymorphism

– 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

Is-a vs. Has-a

– 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.

Is-a vs. Has-a

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.

}

The Java Language

Data types

– 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

Primitive types

– 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

Enum types

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

Declaring and using enums

//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

Special objects

– 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

– Arrays are container objects holding a determined number of elements

– System.arraycopy

– Collections

Operators

– Assignment operator

– Arithmetic operators

– Unary operators

– Equality operators

– Relational operators

– Conditional operators

– instanceof operator

– Bitwise and bitshift operators

– Cast operators

Operator precedence

– expr ++ expr –

– ++ expr -expr + expr expr ~ !

– * / %

– + -

– << >> >>>

– < > <= >= instanceof

– == !=

– &

– ^

– |

– &&

– ||

– ? :

– = += -= *= /= %= &= ^= |= <<= >>= >>>=

Flow control

– if/else

– switch

– For

– While

– Do..while

– For each

If/else

1.

if ((i%2) == 0){

2.

System.out.println("even");

3.

}

4.

else{

5.

System.out.println("odd");

6.

}

Switch

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.

}

For

1.

Byte[] bytes = {1,2,3,4,5};

2.

for (int j = 0; j < bytes.length; j++) {

3.

System.out.println(bytes[j]);

4.

}

For each

1.

for (Byte item : bytes) {

2.

System.out.println(item.byteValue());

3.

}

While

1.

int i=5;

2.

while (i>0){

3.

i--;

4.

System.out.println(bytes[i]);

5.

}

Do While

1.

int i=5;

2.

do{

3.

i--;

4.

System.out.println(bytes[i]);

5.

}while(i>0);

Writing Readable Code

– Javadoc

– Adding javadoc with netbeans

– Naming conventions

– Camel Case

Documenting Your Code

– 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

Documenting Your Code

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.

}

Download