nafSadh's intro to OOP Tools in Java

Object

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.

Real-world objects share 2 characteristics: They all have,
  1. state
  2. behavior

Observe the real-world objects arround you
For each object, ask yourself two questions:
  1. "What possible states can this object be in?"
  2. "What possible behavior can this object perform?"
you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states ( on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

  • Software objects are conceptually similar to real-world objects: they too consist of state and related behavior.
  • An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages)
  • Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
  • Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

Benefits of Object

Bundling code into individual software objects provides a number of benefits, including:

  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

  2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.


Concept of Class

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

Let us have a look as a snippet of class
[Show the Code!]
class Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {
cadence = newValue;
}

void changeGear(int newValue) {
gear = newValue;
}

void speedUp(int increment) {
speed = speed + increment;
}

void applyBrakes(int decrement) {
speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear);
}
}
[hide]

The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.
[Show the Code!]

class BicycleDemo {
public static void main(String[] args) {

// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();

bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}

[hide]
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:

cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

Concept of Inheritance

Different kinds of objects often have a certain amount in common with each other.
for example
Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

  • Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.
  • In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike.
  • In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:
    [Show the pic]

    [hide]

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

Intro to Interfaces...

As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world;
the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
[Show the Code]
interface Bicycle {
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
[hide]
To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration:
[Show the Code]

class ACMEBicycle implements Bicycle {

// remainder of this class implemented as before

}

[hide]

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

What is a Pa.. uhm! Package..?..

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.

The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.

The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation.

Declare a Class

class MyClass {
//field, constructor, and method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class:
  1. constructors for initializing new objects
  2. declarations for the fields that provide the state of the class and its objects,
  3. methods to implement the behavior of the class and its objects

class MyClass extends MySuperClass implements YourInterface {
//field, constructor, and method declarations
}

means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.

In general, class declarations can include these components, in order:
  1. Modifiers such as public, private, and a number of others that you will encounter later.
  2. The class name, with the initial letter capitalized by convention.
  3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  5. The class body, surrounded by braces, {}.

Class Activity with the NetBeans

Declare a Class

Field declarations are composed of three components, in order:
  1. Zero or more modifiers, such as public or private.
  2. The field's type.
  3. The field's name.

Here is an example of a typical method declaration:
[Show]

public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) {

//do the calculation here
}

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.

More generally, method declarations have six components, in order:

  1. Modifiers—such as public, private, and others you will learn about later.
  2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name—the rules for field names apply to method names as well, but the convention is a little different.
  4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
  5. An exception list—to be discussed later.
  6. The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.
[hide]

method signature: Two of the components of a method declaration comprise the method signature—the method's name and the parameter types.

add parameter to the method

Set , Get Methods with each attributes

More on Class

Primitive Types vs. Reference Types
Data types in Java are divided into two categories
  • primitive types
  • reference types (sometimes called nonprimitive types)
The primitive types are boolean, byte, char, short, int, long, float and double. All nonprimitive types are reference types, so classes, which specify the types of objects, are reference types.

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type
Tips
  • Precede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods should be declared public. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)
  • We prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class's fields anywhere in the class outside its method declarations, but scattering them tends to lead to hard-to-read code.
  • Place a blank line between method declarations to separate the methods and enhance program readability.
  • Unless default initialization of your class's instance variables is acceptable, provide a constructor to ensure that your class's instance variables are properly initialized with meaningful values when each new object of your class is created.

On Methods and Class

Static Methods and Satic Fields

Static Class

Class Constants
e.g. Math.PI

P S V M
public static void main (String args[]){}

Multiple Parameters in a method

Method Call Stack

Additional Info on Class

Argument Promotion

Java API Packages
http://java.sun.com/javase/6/docs/api/

Scope of Declarations
[Show]
The basic scope rules are as follows:
  1. The scope of a parameter declaration is the body of the method in which the declaration appears.
  2. The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block.
  3. The scope of a local-variable declaration that appears in the initialization section of a for statement's header is the body of the for statement and the other expressions in the header.
  4. The scope of a method or field of a class is the entire body of the class. This enables non-static methods of a class to use the class's fields and other methods.
[hide]

Method Overloading
The compiler distinguishes overloaded methods by their signaturea combination of the method's name and the number, types and order of its parameters

Intro to Enums

Dip into the Deep of Class : Practical Activity

Declare Another Class
Access Control
this
Constructor Overloading
Default vs. No-Argument Constructors
Notes on Set and Get Methods
Set and Get Methods vs. public Data
Composition
A class can have references to objects of other classes as members. Such a capability is called composition and is sometimes referred to as a has-a relationship
Enumerations
[Show]
Each enum declaration declares an enum class with the following restrictions:
  1. enum types are implicitly final, because they declare constants that should not be modified.
  2. enum constants are implicitly static.
  3. Any attempt to create an object of an enum type with operator new results in a compilation error.
[hide]
Garbage Collection and Method finalize()
static Class Members
[Show]
  • Use a static variable when all objects of a class must use the same copy of the variable.
  • Static class variables and methods exist, and can be used, even if no objects of that class have been instantiated
  • Invoke every static method by using the class name and a dot (.) to emphasize that the method being called is a static method.
  • A compilation error occurs if a static method calls an instance (non-static) method in the same class by using only the method name. Similarly, a compilation error occurs if a static method attempts to access an instance variable in the same class by using only the variable name.
  • Referring to this in a static method is a syntax error.
[hide]
static Import
final Instance Variables

Data Abstraction and Encapsulation

Data Abstraction and Encapsulation
Classes normally hide the details of their implementation from their clients. This is called information hiding. As an example, let us consider the stack data structure introduced in Section 6.6. Recall that a stack is a last-in, first-out (LIFO) data structurethe last item pushed (inserted) on the stack is the first item popped (removed) from the stack.
Stacks can be implemented with arrays and with other data structures, such as linked lists. (We discuss stacks and linked lists in Chapter 17, Data Structures, and in Chapter 19, Collections.) A client of a stack class need not be concerned with the stack's implementation. The client knows only that when data items are placed in the stack, they will be recalled in last-in, first-out order. The client cares about what functionality a stack offers, not about how that functionality is implemented. This concept is referred to as data abstraction. Although programmers might know the details of a class's implementation, they should not write code that depends on these details. This enables a particular class (such as one that implements a stack and its operations, push and pop) to be replaced with another version without affecting the rest of the system. As long as the public services of the class do not change (i.e., every original method still has the same name, return type and parameter list in the new class declaration), the rest of the system is not affected. Most programming languages emphasize actions. In these languages, data exists to support the actions that programs must take. Data is "less interesting" than actions. Data is "crude." Only a few primitive types exist, and it is difficult for programmers to create their own types. Java and the object-oriented style of programming elevate the importance of data. The primary activities of object-oriented programming in Java are the creation of types (e.g., classes) and the expression of the interactions among objects of those types. To create languages that emphasize data, the programming-languages community needed to formalize some notions about data. The formalization we consider here is the notion of abstract data types (ADTs), which improve the program-development process.

Inheritance Idea

about is_a relationaship
SuperClass and SubClass
[Show]
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:
  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
[hide]
protected Members
Constructors in a Subclass and super keyword
the Object class
[sun tutorial]
Overriding and Hiding Methods
[sun tutorial]
Hiding Fields
[sun tutorial]
Polymorphism Policy

Polymorphism enables us to "program in the general" rather than "program in the specific."
Polymorphism enables programmers to deal in generalities and let the execution-time environment handle the specifics. Programmers can command objects to behave in manners appropriate to those objects, without knowing the types of the objects
Demonstrating Polymorphic Behavior
Abstract Classes
an abstract class has no instance
several concrete subclass can inherit abstract class
concrete class can only has instances
Abstract Methods
signature of abstract method is declared in abstract class
inheriting concrete subclass must override and implement the abstract class
instanceof operator
final Methods and Classes
A method that is declared final in a superclass cannot be overridden in a subclass. Methods that are declared private are implicitly final
A class that is declared final cannot be a superclass (i.e., a class cannot extend a final class). All methods in a final class are implicitly final. Class String is an example of a final class.

Facing the Interface

Interfaces
There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
Interfaces in Java
In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces
an example
public interface Implementable {
// constant declarations, if any
// method signatures
returnType methodName(pType param, pType param,..,pType param);
//... }
Interfaces and Multiple Inheritance
The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative. In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement.
The Interface Body
The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon, but no braces, because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public, so the public modifier can be omitted. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.
Interfacing Interfaces...!...?... :-)

Implementing an Interface
public class MyClass implements Implementable {
// method implementations
returnType methodName(pType param, pType param,..,pType param) {
//do something
//return the thing
}
//...
}
Using an Interface as a Type
[sun tutorial]
Rewriting Interfaces
[sun tutorial]
Summary of Interfaces
An interface defines a protocol of communication between two objects.

An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.

A class that implements an interface must implement all the methods declared in the interface.

An interface name can be used anywhere a type can be used.


Summed up OOPs (sUmmarY)

Summary of Creating and Using Classes and Objects
A class declaration names the class and encloses the class body between braces. The class name can be preceded by modifiers. The class body contains fields, methods, and constructors for the class. A class uses fields to contain state information and uses methods to implement behavior. Constructors that initialize a new instance of a class use the name of the class and look like methods without a return type.

You control access to classes and members in the same way: by using an access modifier such as public in their declaration.

You specify a class variable or a class method by using the static keyword in the member's declaration. A member that is not declared as static is implicitly an instance member. Class variables are shared by all instances of a class and can be accessed through the class name as well as an instance reference. Instances of a class get their own copy of each instance variable, which must be accessed through an instance reference.

You create an object from a class by using the new operator and a constructor. The new operator returns a reference to the object that was created. You can assign the reference to a variable or use it directly.

Instance variables and methods that are accessible to code outside of the class that they are declared in can be referred to by using a qualified name. The qualified name of an instance variable looks like this:

objectReference.variableName
                                
The qualified name of a method looks like this:
objectReference.methodName(argumentList) or 
objectReference.methodName()
The garbage collector automatically cleans up unused objects. An object is unused if the program holds no more references to it. You can explicitly drop a reference by setting the variable holding the reference to null.

Summary of Inheritance
Except for the Object class, a class has exactly one direct superclass. A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits. (Note that hiding fields is generally bad programming practice.)

The table in Overriding and Hiding Methods section shows the effect of declaring a method with the same signature as a method in the superclass.

The Object class is the top of the class hierarchy. All classes are descendants from this class and inherit methods from it. Useful methods inherited from Object include toString(), equals(), clone(), and getClass().

You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method.

An abstract class can only be subclassed; it cannot be instantiated. An abstract class can contain abstract methods—methods that are declared but not implemented. Subclasses then provide the implementations for the abstract methods.


Summary of Interfaces
An interface defines a protocol of communication between two objects.

An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.

A class that implements an interface must implement all the methods declared in the interface.

An interface name can be used anywhere a type can be used.


Adfjkg




[Show]
hiddent skfj
[hide]

© nafSadh™ & Khan M Nafee Mostafa Sadh, 2009
http://nafsadh.com/ sadh AT nafsadh DOT com