Sunday, May 28, 2017

Introduction to Java programming, Part-1 (6)

Getting started with the Java language


It is difficult to present the whole Java dialect language structure in a solitary instructional exercise. The rest of Part 1 concentrates on the nuts and bolts of the dialect, abandoning you with enough learning and practice to compose straightforward projects. OOP is about items, so this segment begins with two subjects particularly identified with how the Java dialect handles them: held words and the structure of a Java protest.

Reserved words

Like any programming language, the Java language designates certain words that the compiler recognizes as special. For that reason, you're not allowed to use them for naming your Java constructs. The list of reserved words (also called keywords) is surprisingly short:

abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while


You also may not use truefalse, and null (technically, literals rather than keywords) to name Java constructs
One advantage of programming with an IDE is that it can use syntax coloring for reserved words.

Structure of a Java class

A class is a blueprint for a discrete entity (object) that contains attributes and behavior. The class defines the object's basic structure; at runtime, your application creates an instance of the object. An object has a well-defined boundary and a state, and it can do things when correctly asked. Every object-oriented language has rules about how to define a class.

In the Java language, classes are defined as shown in Listing 1:

Listing 1. Class definition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package packageName;
import ClassNameToImport;
accessSpecifier class ClassName {
  accessSpecifier dataType variableName [= initialValue];
  accessSpecifier ClassName([argumentList]) {
    constructorStatement(s)
  }
  accessSpecifier returnType methodName ([argumentList]) {
    methodStatement(s)
  }
  // This is a comment
  /* This is a comment too */
  /* This is a
     multiline
     comment */
}

Listing 1 contains various types of constructs, including package in line 1, import in line 2, and class in line 3. Those three constructs are in the list of reserved words, so they must be exactly what they are in Listing 1. The names that I've given the other constructs in Listing 1 describe the concepts that they represent.
Notice that lines 11 through 15 in Listing 1 are comment lines. In most programming languages, programmers can add comments to help document the code. Java syntax allows for both single-line and multiline comments:
// This is a comment
/* This is a comment too */
/* This is a
multiline
comment */


A single-line comment must be contained on one line, although you can use adjacent single-line comments to form a block. A multiline comment begins with /*, must be terminated with */, and can span any number of lines.
Next, I'll walk you through the constructs in Listing 1 in detail, starting with package.

Packaging classes


With the Java dialect, you can pick the names for your classes, for example, Account, Person, or LizardMan. Now and again, you may wind up utilizing a similar name to express two somewhat unique ideas. This circumstance, called a name crash, happens regularly. The Java dialect utilizes bundles to determine these contentions. 


A Java bundle is a system for giving a namespace—a range within which names are remarkable, however outside of which they won't not be. To distinguish a develop extraordinarily, you should completely qualify it by including its namespace. 


Bundles likewise give you a decent approach to assemble more-complex applications with discrete units of usefulness. 


To characterize a bundle, utilize the bundle watchword taken after by a lawful bundle name, finishing with a semicolon. Frequently bundle names take after this true standard plan:
package  orgType.orgName.appName.compName;

This package definition breaks down as:

  • orgType is the organization type, such as com, org, or net.
  • orgName is the name of the organization's domain, such as makotojava, oracle, or ibm.
  • appName is the name of the application, abbreviated.
  • compName is the name of the component.

You'll use this convention throughout this tutorial, and I recommend that you keep using it to define all of your Java classes in packages. (The Java language doesn't force you to follow this package convention. You don't need to specify a package at all, in which case all of your classes must have unique names and are in the default package.)

Import statements

Up next in the class definition (referring back to Listing 1) is the import statement. An import statement tells the Java compiler where to find classes that you reference inside of your code. Any nontrivial class uses other classes for some functionality, and the import statement is how you tell the Java compiler about them.
An import statement usually looks like this:
import ClassNameToImport;


You specify the import keyword, followed by the class that you want to import, followed by a semicolon. The class name should be fully qualified, meaning that it should include its package.
To import all classes within a package, you can put .* after the package name. For example, this statement imports every class in the com.makotojava package:
import com.makotojava.*;
Importing an entire package can make your code less readable, however, so I recommend that you import only the classes that you need, using their fully qualified names.

Class declaration

To define an object in the Java language, you must declare a class. Think of a class as a template for an object, like a cookie cutter.
Listing 1 includes this class declaration:
accessSpecifier class ClassName {
  accessSpecifier dataType variableName [= initialValue];
    accessSpecifier ClassName([argumentList]) {
    constructorStatement(s)
  }
  accessSpecifier returnType methodName([argumentList]) {
    methodStatement(s)
  }
}
A class's accessSpecifier can have several values, but usually it's public. You'll look at other values ofaccessSpecifier soon.
You can name classes pretty much however you want, but the convention is to use camel case: Start with an uppercase letter, put the first letter of each concatenated word in uppercase, and make all the other letters lowercase. Class names should contain only letters and numbers. Sticking to these guidelines ensures that your code is more accessible to other developers who are following the same conventions.

Variables and methods

Classes can have two types of membersvariables and methods.

Variables

The values of a class's variables distinguish each instance of that class and define its state. These values are often referred to as instance variables. A variable has:

  • An accessSpecifier
  • A dataType
  • A variableName
  • Optionally, an initialValue
The possible accessSpecifier values are:

  • public: Any object in any package can see the variable. (Don't ever use this value; see the Public variables sidebar.)
  • protected: Any object defined in the same package, or a subclass (defined in any package), can see the variable.
  • No specifier (also called friendly or package private access): Only objects whose classes are defined in the same package can see the variable.
  • private: Only the class containing the variable can see it.
A variable's dataType depends on what the variable is — it might be a primitive type or another class type (more about this later).
The variableName is up to you, but by convention, variable names use the camel case convention, except that they begin with a lowercase letter. (This style is sometimes called lower camel case.)
Don't worry about the initialValue for now; just know that you can initialize an instance variable when you declare it. (Otherwise, the compiler generates a default for you that is set when the class is instantiated.)

Example: Class definition for Person

Here's an example that summarizes what you've learned so far. Listing 2 is a class definition for Person.
Listing 2. Basic class definition for Person
package com.makotojava.intro;
public class Person {
   private String name;
   private int age;
   private int height;
   private int weight;
   private String eyeColor;
   private String gender;
}

This basic class definition for Person isn't useful at this point, because it defines only Person's attributes (and private ones at that). To be more complete, the Person class needs behavior — and that means methods.

Methods

A class's methods define its behavior.
Methods fall into two main categories: constructors; and all other methods, which come in many types. A constructor method is used only to create an instance of a class. Other types of methods can be used for virtually any application behavior.
The class definition back in Listing 1 shows the way to define the structure of a method, which includes elements like:

  • accessSpecifier
  • returnType
  • methodName
  • argumentList
The combination of these structural elements in a method's definition is called the method's signature.
Now take a closer look at the two method categories, starting with constructors.
Constructor methods
You use constructors to specify how to instantiate a class. Listing 1 shows the constructor-declaration syntax in abstract form, and here it is again:
accessSpecifier ClassName([argumentList]) {
  constructorStatement(s)
}


A constructor's accessSpecifier is the same as for variables. The name of the constructor must match the name of the class. So if you call your class Person, the name of the constructor must also be Person.
For any constructor other than the default constructor (see theConstructors are optional sidebar), you pass an argumentList, which is one or more of:
argumentType argumentName
Arguments in an argumentList are separated by commas, and no two arguments can have the same name. argumentType is either a primitive type or another class type (the same as with variable types).
Class definition with a constructor
Now, see what happens when you add the capability to create a Person object in two ways: by using a no-arg constructor and by initializing a partial list of attributes.
Listing 3 shows how to create constructors and also how to use argumentList:
Listing 3. Person class definition with a constructor
package com.makotojava.intro;
public class Person {
  private String name;
  private int age;
  private int height;
  private int  weight;
  private String eyeColor;
  private String gender;
  public Person() {
    // Nothing to do...
  }
  public Person(String name, int age, int height, int weight String eyeColor, String gender) {
    this.name = name;
    this.age = age;
    this.height = height;
    this.weight = weight;
    this.eyeColor = eyeColor;
    this.gender = gender;
  }
}
Note the use of the this keyword in making the variable assignments in Listing 3. The this keyword is Java shorthand for "this object," and you must use it when you reference two variables with the same name. In this case, age is both a constructor parameter and a class variable, so the this keyword helps the compiler to tell which is which.
The Person object is getting more interesting, but it needs more behavior. And for that, you need more methods.
Other methods
A constructor is a particular kind of method with a particular function. Similarly, many other types of methods perform particular functions in Java programs. Exploration of other method types begins in this section and continues throughout the tutorial.
Back in Listing 1, you saw how to declare a method:
accessSpecifier returnType methodName ([argumentList]) {
  methodStatement(s)
}

Other methods look much like constructors, with a couple of exceptions. First, you can name other methods whatever you like (though, of course, certain rules apply). I recommend the following conventions:
  • Start with a lowercase letter.
  • Avoid numbers unless they are absolutely necessary.
  • Use only alphabetic characters.
Second, unlike constructors, other methods have an optional return type.
Person's other methods
Armed with this basic information, you can see in Listing 4 what happens when you add a few more methods to the Person object. (I've omitted constructors for brevity.)
Listing 4. Person with a few new methods
package com.makotojava.intro;
public class Person {
   private String name;
   private int age;
   private int height;
   private int  weight;
   private String eyeColor;
   private String gender;
   public String getName() { return name; }
   public void setName(String value) { name = value; }
   // Other getter/setter combinations...
}


Notice the comment in Listing 4 about "getter/setter combinations." You'll work more with getters and setters later. For now, all you need to know is that a getter is a method for retrieving the value of an attribute, and a setter is a method for modifying that value. Listing 4 shows only one getter/setter combination (for the Name attribute), but you can define more in a similar fashion.
Note in Listing 4 that if a method doesn't return a value, you must tell the compiler by specifying the voidreturn type in its signature.
Static and instance methods
Generally, two types of (nonconstructor) methods are used: instance methods and static methods. Instance methods depend on the state of a specific object instance for their behavior. Static methods are also sometimes called class methods, because their behavior isn't dependent on any single object's state. A static method's behavior happens at the class level.
Static methods are used largely for utility; you can think of them as being global methods (à la C) while keeping the code for the method with the class that defines it.
For example, throughout this tutorial, you'll use the JDK Logger class to output information to the console. To create a Logger class instance, you don't instantiate a Logger class; instead, you invoke a static method named getLogger().
The syntax for invoking a static method on a class is different from the syntax used to invoke a method on an object. You also use the name of the class that contains the static method, as shown in this invocation:
Logger l = Logger.getLogger("NewLogger");

In this example, Logger is the name of the class, and getLogger(...) is the name of the method. So to invoke a static method, you don't need an object instance, just the name of the class.
Previous Post
Next Post

post written by:

0 coment�rios: