Wednesday 31 July 2013

06: Introduction to Java and SDE



Learning Objectives
After completing this session, you will be able to:
  Define a class
  Create objects
  Identify packages, importstatement, and Objectclass
  Explain object messaging
Defining a Class
A class is a basic building block of an object oriented language.
A class is a template that describes the data and the methods thatmanipulate the data.
Examples of class:
  Classroom
  Car
  Person
The following Java program defines a class Person with data member name:
Class Person
private String name;
public void setName(String aName) {
name = aName;
}
public String getName() {
return name;
}
}
The data members in a class can be defined as follows:
  Instance variable:
oThis differentiates one object from another, giving an object its individuality. For
example, the particular name and address for a given Person object is declared as
an instance variable.
oAn instance variable relates to an instance (object) of its class.
  Class variable:
oThe data that is shared by all the objects are declared as class variables.
oThere is only one copy of each of these variables no matter how many objects are
created for the class.
oThese variables exist even if no object of the class has been created. 
oThese variables are also referred to as static fields because they are declared with the keyword static.

oData members of the class are normally declared as instance variables using the keyword private.
Creating Objects
An object is created from a class.
The following statement creates an object:
Person EdmundHillary = new Person();
The preceding statement has three parts:
  Declaration:This notifies the compiler that you will use name to refer to data whose type is type;
Person EdmundHillary
  Instantiation:The new keyword is a Java operator that creates the object.
EdmundHillary = new Person()
  Initialization:The new operator is followed by a call to a constructor. The constructor will contain code that initializes the new object to the desired values.
Packages
  Every class in the Java library belong to a package.
  In the Java API, classes are grouped into packages.
  A class has a full name, which is a combination of the package name and the class name. For example, the class ArrayList is actually java.util.ArrayList.
  To use a class in a package other than java.lang, you must tell Java the full name of the class.
  Packages are important for three main reasons:
oFirstly, they help in the overall organization of a project or library.
oSecondly, packages give you a name-scoping,to help to prevent collisions if many programmers in a company decide to make a class with the same name.
oThirdly, packages provide a level of security, because you can restrict the code, which you write so that only other classes in the same package can access it.
  To put a class in a package, put a package statement at the top of the source code file, before any import statement like package com.mypack;.
  To be in a package, a class must be in a directory structure that exactly matches the package structure. For a class, com.mypack.Book, the Book class must be in a directory named mypack, which is in a directory named com.
  Organizing your classes into packages prevents naming collisions with other classes, if you preponed your reverse domain name on to the front of a class name. 
Import Statement
A typical set of import statements might look like the following:
  import java.io.*;
  import java.util.ArrayList;


  import java.util.Date;

  import java.util.Properties;
The import statements must come right after the package statement, before the class statement.
Purpose of import statement:
  Because of the rigid source code naming convention, the Java compiler can easily find the corresponding source or class files justfrom the fully qualified name of a package and class. This can be illustrated with the following example:
java.util.ArrayList myList = new java.util.ArrayList(50);
  The alternative to this long-winded style of coding (as shown earlier), is to use import
statements like the following:
import java.util.ArrayList;
ArrayList myList = new ArrayList(50);
To derive a class from an external superclass, you must first import the superclass using the import statement.
Object Class
Every class in Java extends class Object that is the Object class is the mother of all classes. It is the superclass of everything.
Any class that does not explicitly extend anotherclass, implicitly extends Object class.
Few of the important methods of the Object class are as follows:
  equals(Object obj): Indicates whether some other object is "equal to" this one and it returns a boolean value as true or false
  toString():Returns a string representation of the object
  hashCode():Returns a hash code value (of integer type) for the object
Object Messaging
  Objects cooperate and communicate with other objects in a program by passing messages to one another (setting a value, returning a value, or sending an email).
  When an object invokes a method on itself or on the method of another object, it is  said to pass a message to the object that contains the target method.
  The message contains the name of the method and any data that the method
requires.
  Example: person.setName(“EdmundHillary”);
  Data that are passed to a method are known as arguments. The required arguments for a method are defined by a parameter list of the method.
  After performing the operation, the body of the method uses the return statement to return the value to the calling object.
  thiskeyword:
oUsed to represent the object that invokes the method:
oUsed within the member methods of the class those are not static 



this keyword
  thiskeyword refers to the object that is currently executing.
  thiskeyword also allows one constructor to explicitly invoke another constructor in the same class.
  It is useful for a method to refer to instance variables relative to thiskeyword when alocal variable hides the data member with the same name, like the following code:
Class Person {
String name;
Person(String name) {
this.name = name;
}
…….
}
Try It Out
Problem Statement:
Illustrate the importance of the objects withrelevant to entries in the address book.
Code:
class AddressBook {
String id;
int telephoneNumber;
public void getName() { }
public String setName(String aName) { }
public String changeName(String aName) { }
}
Refer File Name: AddressBook.javato obtain soft copy of the program code
How It Works:
  One analogy for objects is a packet of unused visiting cards in the address book.
  Each card has the same blank fields (the instance variables).
  When you fill out a card, you are creatingan instance (object), and the entries youmake on that card represent its state.
  The methods of the class are the things you do to a particular card.
  getName() , changeName(String aName) , and setName(String aName) could all bethe methods for the class AddressBook.
  So, each card can do the same things (getName() , setName(String aName) ,and so on), but each card knows things unique to that particular card.
 
Tips and Tricks
What if you have a hundred classes or a thousand? Is not that a big pain to deliver all those individual files? Can these classes be bundled into one application thing?
Solution:Yes, it would be a big pain to deliver a huge bunch of individual files to your end-users,but you will not have to. You can put all of your application files into a Java Archive or a .jar file that is based on the pkzip format. In the jar file, you can include a simple text file formatted as something called a manifest, that defines which class in that jar holds the main() method that should run.
Summary
  Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier.
  A class describes how to make an object of that class type. A class is like a blueprint.
  An object knowsthings and doesthings.
  The things an object knows about itself are called instance variables. They represent the state of an object.
  The things an object does are called methods. They represent the behaviour of an object

07:The main()method and SOP (System.out.printlnmethod)



The main Method
  In Java, everything goes in a class. The source code is typed into a file (with a .java extension). This is then compiled into a new class file (with a .class extension)
  When you run your program, you are really running a class.
  Running a program means telling the Java Virtual Machine (JVM) to “Load the class”  (Book class for example), then starting to execute its main() method. Keep running till all the code in main() method is finished.
  The main() method is where a Java application starts running.
  Every Java application has to have at least one class, and at least one main() method.
  The main() method will be written as shown in the following code:
public static void main (String[] args) {
// your code goes here
}
  Uses of main()method:
oTo test your real class
oTo launch or start your Java application
The System.out.println (SOP) Method
  The System class is available in the java.lang package.
  The “out” is a field of the System class representing the “standard” output stream.
  Typically this stream corresponds to display output or another output destination
specified by the host environment or user.
  For simple stand-alone Java applications, a typical way to write a line of output data is
System.out.println(data) .
  System.out.println inserts a new line while System.out.print keeps printing to the same line.
Code Structure in Java
  Put a class in a source file
  Put methods in a class
  Put statements in a method
Example
/**
*
* Sample program to print This is my first Java program
*
*/
class MyFirstProgram { // Declare class MyFirstProgram
void displayMessage() {
System.out.println(“This is my first Java program”);
}
public static void main(String[] args) {
MyFirstProgram myFirstProgram = new MyFirstProgram();
myFirstProgram.displayMessage();
}
}
Save the preceding contents in a file called MyFirstProgram.java
Compile and Run a Java Program
Compile:To compile MyFirstProgram.java source file in a MS-DOS prompt, give the following
command:
javac MyFirstProgram.java
After successfully compiling the earlier source file, the compiler generates MyFirstProgram.class
file, which is made up of bytecodes. The compiled bytecode is platform independent.
Run: To run the earlier Java program in a MS-DOS prompt, give the following command:
java MyFirstProgram
The JVM translates the bytecode into something that the underlying platform understands, and runs your program.
The following output will be displayed in the command prompt after running the earlier command:
This is my first Java program
Try It Out
Problem Statement:
Illustrate the basic structure ofa Java application program.
Code:
/**
* A Simple application.
*/
public class SimpleApp1 {
public static void main(String args[]) {
// A method to output to the console.
System.out.println("Simple program");
}
}
Refer File Name: SimpleApp1.javato obtain soft copy of the program code
How It Works:
  /**
* A Simple application.*/:A comment describing the program
  public class SimpleApp1 {:Begin with the class specification
  public static void main(String args[]) {:Required method for
application programs
  // A method to output to the console.:Comment using two slashes
  System.out.println("Simple program");:Print to console
  }:Curly braces span the code for a class. They also bracket the code of a method.
Tips and Tricks
Does a Java program need to have a main() method in every class written?
Solution:No, a Java program might use dozens of classes (even hundreds),but you might have
only one with a main() method, the one that starts the running of the program. You might write test
classes, though, that have main methods for testing your other classes.
Summary
  The method signature for the main method in a Java application is as follows:
public static void main(String[] args)
  Briefly explain the reason that the main method in a Java application is declared
public.
  The keyword public indicates that the method can be called by any object.
  Explain the reason that the main method in a Java application must be declared static.
  The keyword static indicates that the method is a classmethod which can be called without the requirement to instantiate an object of the class. This is used by the Java interpreter to launch the program by invokingthe main method of the class identified in the command to start the program.
  Describe the purpose of the keyword void when used as the return type for the main method.
  The void keyword when used as the return type for any Java methods indicates that the method does not return anything.