Sei sulla pagina 1di 34

public class MainClass { public static void main(String[] args) { int x = 9; if (x > 4) { // statements } }

The for statement is like the while statement, i.e. you use it to create loop. The for statement has fo syntax:
for ( init ; booleanExpression ; update ) { statement (s) }

1. init is an initialization that will be performed before the first iteration. 2. booleanExpression is a boolean expression which will cause the execution of statement(s) if to true. 3. update is a statement that will be executed after the execution of the statement block. 4. init, expression, and update are optional. The for statement will stop only if one of the following conditions is met: 1. booleanExpression evaluates to false 2. A break or continue statement is executed 3. A runtime error occurs.
public class Main { public static void main(String[] args) { for (int i = 0, j = 1, k = 2; i < 5; i++){ System.out.println("I : " + i + ",j : " + j + ", k : " + k); } } } /* I : 0,j : 1, k : 2 I : 1,j : 1, k : 2 I : 2,j : 1, k : 2 I : 3,j : 1, k : 2 I : 4,j : 1, k : 2 */

The For-Each Version of the for Loop


The general form of the for-each version of the for is shown here:
for(type itr-var : iterableObj) statement-block

The object referred to by iterableObj must be an array or an object that implements the new Iterable

Use a for-each style for loop


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

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; // use for-each style for to display and sum the values for(int x : nums) { System.out.println("Value is: " + x); sum += x; } System.out.println("Summation: " + sum); } }

Using 'for each' to loop through array


public class MainClass { public static void main(String[] arg) { char[] vowels = { 'a', 'e', 'i', 'o', 'u'}; for(char ch: vowels){ System.out.println(ch); } } }

The switch Statement

1. An alternative to a series of else if is the switch statement. 2. The switch statement allows you to choose a block of statements to run from a selection of c on the return value of an expression. 3. The expression used in the switch statement must return an int or an enumerated value. The syntax of the switch statement is as follows.
switch (expression) { case value_1 : statement (s); break; case value_2 : statement (s); break; . . . case value_n : statement (s); break; default: statement (s); }

Failure to add a break statement after a case will not generate a compile error but may have more s consequences because the statements on the next case will be executed. Here is an example of the switch statement:
public class MainClass { public static void main(String[] args) { int i = 1; switch (i) { case 1 : System.out.println("One."); break; case 2 : System.out.println("Two."); break; case 3 : System.out.println("Three."); break; default: System.out.println("You did not enter a valid value."); } } }

The switch Statement: a demo


public class MainClass { public static void main(String[] args) { int choice = 2; switch (choice) { case 1: System.out.println("Choice 1 selected"); break; case 2: System.out.println("Choice 2 selected"); break; case 3: System.out.println("Choice 3 selected"); break; default: System.out.println("Default"); break; } } }

What Is a Java Class?


Classes are the fundamental building blocks of a Java program.

You can define an Employee class as follows:


class Employee { int age; double salary; }

1. 2. 3. 4.

By convention, class names capitalize the initial of each word. For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. This type of naming convention is known as Pascal naming convention. The other convention, the camel naming convention, capitalize the initial of each word, excep word.

5. Method and field names use the camel naming convention.

Fields
1. Fields are variables. 2. They can be primitives or references to objects. For example, the Employee class has two fields, age and salary.
public class Employee{ int age; int salary }

1. Field names should follow the camel naming convention. 2. The initial of each word in the field, except for the first word, is written with a capital letter. 3. For example: age, maxAge, address, validAddress, numberOfRows. Defining Classes: A class has fields and methods
public class MainClass { private int aField; public void aMethod() { } }

Creating Objects of a Class


class Sphere { double radius; // Radius of a sphere Sphere() {

} // Class constructor Sphere(double theRadius) { radius = theRadius; // Set the radius } } public class MainClass { public static void main(String[] arg){ Sphere sp = new Sphere(); } }

Checking whether the object referenced was of type String


class Animal { public Animal(String aType) { type = aType; } public String toString() { return "This is a " + type; } private String type; } public class MainClass { public static void main(String[] a) { Animal pet = new Animal("a"); if (pet.getClass() == Animal.class) { System.out.println("it is an animal!"); } } }

Class declaration with one method

public class MainClass { public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook(); myGradeBook.displayMessage(); } }

class GradeBook {

public void displayMessage() { System.out.println( "Welcome to the Grade Book!" ); } }

Class declaration with a method that has a parameter


public class MainClass { public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook(); String courseName = "Java "; myGradeBook.displayMessage( courseName ); } } class GradeBook { public void displayMessage( String courseName ) { System.out.printf( "Welcome to the grade book for\n%s!\n", courseName ); } }

Class that contains a String instance variable and methods to set a its value
public class MainClass { public static void main( String args[] ) { GradeBook myGradeBook = new GradeBook();

System.out.printf( "Initial course name is: %s\n\n",myGradeBook.getCourseName() ) String theName = "Java"; myGradeBook.setCourseName( theName ); // set the course name } } class GradeBook { private String courseName; // course name for this GradeBook myGradeBook.displayMessage();

// method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // method to retrieve the course name public String getCourseName() { return courseName; } // display a welcome message to the GradeBook user public void displayMessage() { System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() ); } }

Class with a constructor to initialize instance variables


public class MainClass { public static void main( String args[] ) { Account account1 = new Account( 50.00 ); // create Account object Account account2 = new Account( -7.53 ); // create Account object System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() ); double depositAmount; // deposit amount read from user depositAmount = 10.10; account1.credit( depositAmount ); // add to account1 balance System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() ); depositAmount = 12.12; account2.credit( depositAmount ); // add to account2 balance System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n", account2.getBalance() );

} }

class Account { private double balance; // instance variable that stores the balance // constructor

public Account( double initialBalance ) { if ( initialBalance > 0.0 ) balance = initialBalance; } public void credit( double amount ) { balance = balance + amount; } public double getBalance() { return balance; } }

Constructor If no user defined constructor is provided for a class, compiler initializes member variables to its default values.

numeric data types are set to 0 char data types are set to null character(\0) reference variables are set to null

In order to create a Constructor observe the following rules 1) It has the same name as the class 2) It should not return a value not even void

Assignment 1: Create your First Constructor

Step 1: Type following code in your editor


class Demo{ int value1; int value2;

Demo(){ value1 = 10; value2 = 20; System.out.println("Inside Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); d1.display(); } }

Step 2) Save , Run & Compile the code. Observe the output.

constructor overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type Examples of valid constructors for class Account are
Account(int a); Account (int a,int b); Account (String a,int b);

Assignment 2:To understand Constructor Overloading

Step 1) Type the code in editor


class Demo{ int value1; int value2; /*Demo(){ value1 = 10; value2 = 20; System.out.println("Inside 1st Constructor"); }*/

} Demo(int a,int b){ value1 = a; value2 = b; System.out.println("Inside 3rd Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); Demo d2 = new Demo(30); Demo d3 = new Demo(30,40); d1.display(); d2.display(); d3.display(); } }

Demo(int a){ value1 = a; System.out.println("Inside 2nd Constructor");

Step 2) Save , Compile & Run the Code.

Step 3) Error = ?. Try and debug the error before proceeding to next step.

Step 4) Every class has a default Constructor. Default Constructor for class Demo is Demo(). In case you do not provide this constructor the compiler creates it for you and initializes the variables to default values. You may choose to override this default constructor and initialize variables to your desired values as shown in Assignment 1. But if you specify a parametrized constructor like Demo(int a) ,and want to use the default constructor Demo(), it is mandatory for you to specify it. In other words, in case your Constructor is overridden , and you want to use the default constructor , its need to be specified.

Step 4) Uncomment line # 4-8. Save , Compile & Run the code.

constructor chaining
Consider a scenario where a base class is extended by a child . Whenever an object of the child class is created , the constructor of the parent class is invoked first. This is called Constructor chaining.

Assignment 3: To understand constructor chaining

Step1 ) Copy the following code in the editor


class Demo{ int value1; int value2; Demo(){ value1 = 1; value2 = 2; System.out.println("Inside 1st Parent Constructor"); } Demo(int a){ value1 = a; System.out.println("Inside 2nd Parent Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ DemoChild d1 = new DemoChild(); d1.display(); } } class DemoChild extends Demo{ int value3; int value4; DemoChild(){ //super(5); value3 = 3; value4 = 4; System.out.println("Inside the Constructor of Child"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2);

System.out.println("Value1 === "+value3); System.out.println("Value2 === "+value4); } }

Step 2) Run the Code. Owing to constructor chaining , when object of child class DemoChild is created , constructor Demo() of the parent class is invoked first and later constructor DemoChild() of the child is created. Expected Output =
Inside Inside Value1 Value2 Value1 Value2 1st the === === === === Parent Constructor Constructor of Child 1 2 3 4

Step3 ) You may observe the constructor of the parent class Demo is overridden . What is you want to call the overridden constructor Demo(int a) instead of the default constructor Demo() when your child object is created ??? In such cases you can use the keyword "super" to call overridden constructors of the parent class.

Syntax:super(); --or-super(parameter list);

Ex: If your constructor is like Demo(String Name,int a) you will specify super("Java",5)

If used ,the keyword super needs to be the first line of code in the constructor of the child class.

Step 4) Uncomment Line # 26 and run the code. Observe the Output

Order of constructor calls


class Meal { Meal() { System.out.println("Meal()"); } } class Bread { Bread() { System.out.println("Bread()"); } } class Cheese { Cheese() { System.out.println("Cheese()"); } } class Lettuce { Lettuce() { System.out.println("Lettuce()"); } } class Lunch extends Meal { Lunch() { System.out.println("Lunch()"); } } class PortableLunch extends Lunch { PortableLunch() { System.out.println("PortableLunch()"); } } class Sandwich extends PortableLunch { private Bread b = new Bread(); private Cheese c = new Cheese(); private Lettuce l = new Lettuce(); public Sandwich() { System.out.println("Sandwich()"); } } public class MainClass { public static void main(String[] args) {

} }

new Sandwich();

Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() Sandwich() Method Overloading

Java allows you to have multiple methods having the same name, as long as method accept different sets of argument types. In other words, in our ex is legal to have these two methods in the same class.
public String printString(String string) public String printString(String string, int offset)

This technique is called method overloading. The return value of the meth taken into consideration. As such, these two methods must not exist in th class:
public int countRows(int number); public String countRows(int number);

Using Method Overloading


A method's name with the types and sequence of the parameters form the method's signature
public class MainClass { public void print(int a) { System.out.println(a); } public void print(String a) { System.out.println(a); } }

Overloading based on the order of the arguments


public class MainClass { static void print(String s, int i) { System.out.println("String: " + s + ", int: " + i); }

static void print(int i, String s) { System.out.println("int: " + i + ", String: " + s); } public static void main(String[] args) { print("String first", 11); print(99, "Int first"); } }

String: String first, int: 11 int: 99, String: Int first Using overloaded methods to print array of different types
public class MainClass { // method printArray to print Integer array public static void printArray(Integer[] inputArray) { // display array elements for (Integer element : inputArray) System.out.printf("%s ", element); System.out.println(); } // method printArray to print Double array public static void printArray(Double[] inputArray) { // display array elements for (Double element : inputArray) System.out.printf("%s ", element); System.out.println(); } // method printArray to print Character array public static void printArray(Character[] inputArray) { // display array elements for (Character element : inputArray) System.out.printf("%s ", element); System.out.println(); } public static void main(String args[]) { // create arrays of Integer, Double and Character Integer[] integerArray = { 1, 2, 3, 4, 5, 6 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("Array integerArray contains:"); printArray(integerArray); // pass an Integer array System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); // pass a Double array System.out.println("\nArray characterArray contains:"); printArray(characterArray); // pass a Character array } }

Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array characterArray contains: H E L L O
class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a + 10); return temp; }

class ReturnObjectTest { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: " + ob2.a); } }

Creating Objects
1. Using the new keyword. 2. new is always followed by the constructor of the class. For example, to create an Employee object, you write:
Employee employee = new Employee();

Here, 'employee' is an object reference of type Employee. 1. Once you have an object, you can call its methods and access its fields, by using the object 2. You use a period (.) to call a method or a field. For example:
objectReference.methodName objectReference.fieldName

The following code, for instance, creates an Employee object and assigns values to its age and sala

public class MainClass { public static void main(String[] args) { Employee employee = new Employee(); employee.age = 24; employee.salary = 50000; } } class Employee { public int age; public double salary; public Employee() { } public Employee(int ageValue, double salaryValue) { age = ageValue; salary = salaryValue; } }

Creating Objects
1. Using the new keyword. 2. new is always followed by the constructor of the class. For example, to create an Employee object, you write:
Employee employee = new Employee();

Here, 'employee' is an object reference of type Employee. 1. Once you have an object, you can call its methods and access its fields, by using the object 2. You use a period (.) to call a method or a field. For example:
objectReference.methodName objectReference.fieldName public class MainClass { public static void main(String[] args) { Employee employee = new Employee(); employee.age = 24; employee.salary = 50000; } } class Employee { public int age; public double salary; public Employee() { }

The following code, for instance, creates an Employee object and assigns values to its age and sala

public Employee(int ageValue, double salaryValue) { age = ageValue; salary = salaryValue; } }

Inheritance
1. 2. 3. 4. 5. 6.

You extend a class by creating a new class. The former and the latter will then have a parent-child relationship. The original class is the parent class or the base class or the superclass. The new class is called a child class or a subclass or a derived class of the parent. The process of extending a class in object-oriented programming is called inheritance. In a subclass you can add new methods and new fields as well as override existing methods class to change their behaviors. 7. Inheritance gives you the opportunity to add some functionality that does not exist in the orig 8. Inheritance can also change the behaviors of the existing class to better suit your needs. 9. The subclass and the superclass has an "is-a" relationship. Accessibility

Within a subclass you can access its superclass's public and protected methods and fields , but superclass's private methods. If the subclass and the superclass are in the same package, y access the superclass's default methods and fields.
public class P { public void publicMethod() { } protected void protectedMethod() { } void defaultMethod() { }

class C extends P { public void testMethod() { publicMethod(); protectedMethod(); defaultMethod(); } }

Method Overriding

1. When you extends a class, you can change the behavior of a method in the parent class. 2. This is called method overriding. 3. This happens when you write in a subclass a method that has the same signature as a meth parent class. 4. If only the name is the same but the list of arguments is not, then it is method overloading.
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. Consider the following: // Method overriding. class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j);

} } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // display k this overrides show() in A void show() { System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } } The output produced by this program is shown here: k: 3 When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the versio n of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass' version. This allows all instance variables to be displayed. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show()

System.out.println("k: " + k); } } If you substitute this version of A into the previous program, you will see the following output: i and j: 1 2 k: 3 Here, super.show( ) calls the superclass version of show( ). Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. For example, consider this modified version of the preceding example: // Methods with differing type signatures are overloaded not // overridden. class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // overload show() void show(String msg) { System.out.println(msg + k);

} } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show("This is k: "); // this calls show() in B subOb.show(); // this calls show() in A } } The output produced by this program is shown here: This is k: 3 i and j: 1 2 The version of show( ) in B takes a string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes place.

The extends Keyword


You extend a class by using the extends keyword in a class declaration, The Parent class
public class Parent { }

The Child class


public class Child extends Parent { }

Deriving a Class
class Animal { public Animal(String aType) { type = aType; } public String toString() { return "This is a " + type; } private String type; } class Dog extends Animal { public Dog(String name){ super(name); } private String breed; }

The keyword super represents an instance of the direct superclass current object.

1. You can explicitly call the parent's constructor from a subclass's constructor by using the sup 2. 'super' must be the first statement in the constructor.
class Parent { public Parent(){ } } public class Child extends Parent { public Child () { super(); } }

Overriding a Base Class Method


class Animal { public Animal(String aType) { type = new String(aType); } public String toString() { return "This is a " + type; } private String type; } class Dog extends Animal { public Dog(String aName) { super("Dog"); name = aName; breed = "Unknown"; } public Dog(String aName, String aBreed) { super("Dog"); name = aName; breed = aBreed; } public String toString() { return "It's " + name + " the " + breed; } private String name; private String breed; }

Demonstrate when constructors are called in a Multilevel Hierarch


class A { A() {

} }

System.out.println("Inside A's constructor.");

class B extends A { B() { System.out.println("Inside B's constructor."); } } class C extends B { C() { System.out.println("Inside C's constructor."); } } class CallingCons { public static void main(String args[]) { C c = new C(); } }

The this Keyword


You use the this keyword from any method or constructor to refer to the current object.
public class Box { int length; int width; int height; public Box(int length, int width, int height) { this.length = length; this.width = width; this.height = height; } }

Creating a Thread

A thread is a basic processing unit to which an operating system allocates processor time, and mor thread can be executing code inside a process. (Java 5: A Beginner's Tutorial by Budi Kurniawan B Software Corp. 2006 Every Java program has at least one thread, the thread that executes the Java program. It is create invoke the static main method of your Java class. There are two ways to create a thread. 1. Extend the java.lang.Thread class 2. Implement the java.lang.Runnable interface. 1. Once you have a Thread object, you call its start method to start the thread. 2. When a thread is started, its run method is executed.

3. Once the run method returns or throws an exception, the thread dies and will be garbage-col Every Thread has a state and a Thread can be in one of these six states. 1. new. A state in which a thread has not been started. 2. runnable. A state in which a thread is executing. 3. blocked. A state in which a thread is waiting for a lock to access an object. 4. waiting. A state in which a thread is waiting indefinitely for another thread to perform an actio 5. timed__waiting. A state in which a thread is waiting for up to a specified period of time for an

to perform an action.

6. terminated. A state in which a thread has exited. The values that represent these states are encapsulated in the java.lang.Thread.State enum. The m this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED. Creating Thread: Deriving a Subclass of Thread
import java.io.IOException; class TryThread extends Thread { public TryThread(String firstName, String secondName, long delay) { this.firstName = firstName; this.secondName = secondName; aWhile = delay; setDaemon(true); } public void run() { try { while (true) { System.out.print(firstName); sleep(aWhile); System.out.print(secondName + "\n"); } } catch (InterruptedException e) { System.out.println(firstName + secondName + e); } } private String firstName; private String secondName; private long aWhile; } public class MainClass { public static void main(String[] args) { Thread first = new TryThread("A ", "a ", 200L); Thread second = new TryThread("B ", "b ", 300L); Thread third = new TryThread("C ", "c ", 500L); System.out.println("Press Enter when you have had enough...\n"); first.start(); second.start(); third.start(); try { System.in.read(); System.out.println("Enter pressed...\n"); } catch (IOException e) { System.out.println(e); } return; } }

Create a second thread.


class NewThread implements Runnable {

Thread t; NewThread() { t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); }

class ThreadDemo { public static void main(String args[]) { new NewThread(); try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }

Create a second thread by extending Thread


class NewThread extends Thread { NewThread() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); }

} }

System.out.println("Exiting child thread.");

class ExtendThread { public static void main(String args[]) { new NewThread(); // create a new thread try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting.");

} }

Create multiple threads.


class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { Thread.sleep(10000);

} catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } } } System.out.println("Main thread exiting.");

What Is a 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. The following Bicycle class is one possible implementation of a bicycle:
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); }

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. Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:
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();

} }

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

What Is an Interface?
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:
interface Bicycle { // wheel revolutions per minute

void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); } void applyBrakes(int decrement);

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle { // remainder of this class // implemented as before }

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.

Defining an Interface
An interface declaration consists of modifiers, the keyword interface, the interface name, a commaseparated list of parent interfaces (if any), and the interface body. For example:
public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations // // base of natural logarithms double E = 2.718282; // method signatures void doSomething (int i, double x); int doSomethingElse(String s); }

The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface. An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.

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.

Implementing an Interface
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a commaseparated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

A Sample Interface, Relatable


Consider an interface that defines how to compare the size of objects.
public interface Relatable { // this (object calling isLargerThan) // and other must be instances of // the same class returns 1, 0, -1 // if this is greater // than, equal // to, or less than other public int isLargerThan(Relatable other); }

If you want to be able to compare the size of similar objects, no matter what they are, the class that instantiates them should implement Relatable. Any class can implement Relatable if there is some way to compare the relative "size" of objects instantiated from the class. For strings, it could be number of characters; for books, it could be number of pages; for students, it could be weight; and so forth. For planar geometric objects, area would be a good choice (see the RectanglePlus class that follows), while volume would work for three-dimensional geometric objects. All such classes can implement the isLargerThan() method. If you know that a class implements Relatable, then you know that you can compare the size of the objects instantiated from that class.

Implementing the Relatable Interface


Here is the Rectangle class that was presented in the Creating Objects section, rewritten to implement Relatable.
public class RectanglePlus implements Relatable { public int width = 0; public int height = 0; public Point origin; // four constructors public RectanglePlus() { origin = new Point(0, 0); } public RectanglePlus(Point p) { origin = p; } public RectanglePlus(int w, int h) { origin = new Point(0, 0); width = w; height = h; } public RectanglePlus(Point p, int w, int h) { origin = p; width = w; height = h; } // a method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; } // a method for computing // the area of the rectangle public int getArea() { return width * height; } // a method required to implement // the Relatable interface public int isLargerThan(Relatable other) { RectanglePlus otherRect = (RectanglePlus)other; if (this.getArea() < otherRect.getArea()) return -1; else if (this.getArea() > otherRect.getArea()) return 1; else return 0; } }

Because RectanglePlus implements Relatable, the size of any two RectanglePlus objects can be compared. Note: The isLargerThan method, as defined in the Relatable interface, takes an object of type Relatable. The line of code, shown in bold in the previous example, casts other to a RectanglePlus instance. Type casting tells the compiler what the object really is. Invoking getArea directly on the other instance (other.getArea()) would fail to compile because the compiler does not understand that other is actually an instance of RectanglePlus.

Potrebbero piacerti anche