Thursday, 26 March 2015

Class, Object, LOOPs



Classes
The introduction to object-oriented concepts in the lesson titled Object-oriented Programming Concepts used a Test class as an example, with num1, num2 fields. Here is sample code for a possible implementation of a Test class, to give you an overview of a class declaration

Declaring Classes 

You've seen classes defined in the following way:
 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: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behaviour of the class and its objects.
Declaring Member Variables
There are several kinds of variables:
·         Member variables in a class—these are called fields.
·         Variables in a method or block of code—these are called local variables.
·         Variables in method declarations—these are called parameters.

class Test
{
// the Test class has two fields
public int num1; 
public int num2;   // num1 and num2 are fields
public void method1(int a)  // variable a is called parameters
{
Int a;  // local variables
.........
.........
}
}  // end of class Test

The Test class uses the following lines of code to define its fields:

public int num1;
public int num2;
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.

The fields of Test are named num1 and num2 and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.

 

Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some

Examples:
run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

Note:-
Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.

 

Overloading Methods

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists 
public class DataArtist 
{    ...
    public void draw(String s)  {
        ...
    }
    public void draw(int i) {
        ...
    }
    public void draw(double f)  {
        ...
    }
    public void draw(int i, double f)  {
        ...
    }
} 

Constructors for Your Classes

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.
For example, Test has one constructor: 
public Test(int a, int b) // two parameter constructor
{
    num1 = a;
    num2 = b;
} 
To create a new Test object called obj, a constructor is called by the new operator: 
Test obj = new Test(30,8); 
new Test(30,8) creates space in memory for the object and initializes its fields.
Although Test only has one constructor, it could have others, including a no-argument constructor.

public Test() 
{
    num1 = 1;
    num2 = 10;
}
 Test obj = new Test(); invokes the no-argument constructor to create a new Test object called obj1.

Creating Objects

A class provides the blueprint for objects; you create an object from a class. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.


ClassName objectName=new ClassConstructor();

Example:-
Test obj = new Test(); 

LOOPS in JAVA
1.      for
2.      while
3.      do -while
4.      for-each
Java for loop used to repeat execution of statement(s) until a certain condition holds true. for  is a keyword in Java programming language.
 Java for loop syntax
for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {
  // Statements to execute i.e. Body of for loop
} 
Example:-
class ForLoop 
{
  public static void main(String[] args) 
    {
    int c;
     for (c = 1; c <= 10; c++) 
    {
      System.out.println(c);
    }
  }
}
 Example for Infinite loop
 // Infinite for loop
for (;;) 
{
  System.out.println("Java programmer");
}
 Note:- You can terminate an infinite loop by pressing Ctrl+C.

 Java while loop

Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. First of all lets discuss while loop syntax:
 while (condition(s))
{
// Body of loop
}
 Example:-
import java.util.Scanner;
class BreakWhileLoop {
  public static void main(String[] args) {
    int n;
    Scanner input = new Scanner(System.in);
    while (true) {
      System.out.println("Input an integer");
      n = input.nextInt();
      if (n == 0) {
        break;
      }
      System.out.println("You entered " + n);
    }
  }
}
do-while loop in JAVA

The Java programming language also provides a do-while statement, which can be expressed as follows:
do {
     statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Advantage of for-each loop:

  • It makes the code more readable.
  • It eliminates the possibility of programming errors.

Syntax of for-each loop:

for(data_type variable : array ){ .........}  

 Example :-

class ForEachExample1
{  
  public static void main(String args[])
{  
   int arr[]={12,13,14,44};  
   for(int i:arr)
   {  
     System.out.println(i);  
   }  
 }   
}  







No comments:

Post a Comment