Quantcast

P^i

Your Online Tech Magazine

Fri05242013

Last update12:17:26 PM

Back You are here: Home More Programming and Web Programming Chapter 1 : Introduction to JAVA

Chapter 1 : Introduction to JAVA



A Java program is mostly a collection of objects talking to other objects by invoking each other's methods. Every object is of a certain type, and that type is defined by a class or an interface. Most Java programs use a collection of objects of many different types.

  • Class A template that describes the kinds of state and behavior that objects of its type support.
  • Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class.
  • State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state.
  • Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class' logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.

 

Identifiers and Keywords

All the Java components we just talked about—classes, variables, and methods— need names. In Java these names are called identifiers, and, as you might expect, there are rules for what constitutes a legal Java identifier. Beyond what's legal, though, Java programmers (and Sun) have created conventions for naming methods, variables, and classes. Like all programming languages, Java has a set of built-in keywords. These keywords must not be used as identifiers. Later in this chapter we'll review the details of these naming rules, conventions, and the Java keywords.

Inheritance

Central to Java and other object-oriented languages is the concept of inheritance, which allows code defined in one class to be reused in other classes. In Java, you can define a general (more abstract) superclass, and then extend it with more specific subclasses. The superclass knows nothing of the classes that inherit from it, but all of the subclasses that inherit from the superclass must explicitly declare the inheritance relationship. A subclass that inherits from a superclass is automatically given accessible instance variables and methods defined by the superclass, but is also free to override superclass methods to define more specific behavior. For example, a Car superclass class could define general methods common to all automobiles, but a Ferrari subclass could override the accelerate() method.

Interfaces

A powerful companion to inheritance is the use of interfaces. Interfaces are like a 100-percent abstract superclass that defines the methods a subclass must support, but not how they must be supported. In other words, an Animal interface might declare that all Animal implementation classes have an eat() method, but the Animal interface doesn't supply any logic for the eat() method. That means it's up to the classes that implement the Animal interface to define the actual code for how that particular Animal type behaves when its eat() method is invoked.

Finding Other Classes

It's a good idea to make your classes cohesive. That means that every class should have a focused set of responsibilities. For instance, if you were creating a zoo simulation program, you'd want to represent aardvarks with one class, and zoo visitors with a different class. In addition, you might have a Zookeeper class, and a Popcorn vendor class. The point is that you don't want a class that has both Aardvark and Popcorn behaviors. Even a simple Java program uses objects from many different classes: some that you created, and some built by others (such as Sun's Java API classes). Java organizes classes into packages, and uses import statements to give programmers a consistent way to manage naming of, and access to, classes they need. The exam covers a lot of concepts related to packages and class access;


Identifiers & JavaBeans

we'll start with Java identifiers. The three aspects of Java identifiers that we cover here are

  • Legal Identifiers The rules the compiler uses to determine whether a name is legal.
  • Sun's Java Code Conventions Sun's recommendations for naming classes, variables, and methods. We typically adhere to these standards throughout the book, except when we're trying to show you how a tricky exam question might be coded.
  • JavaBeans Naming Standards The naming requirements of the JavaBeans specification.

Legal Identifiers

Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).

  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • In practice, there is no limit to the number of characters an identifier can contain.
  • You can't use a Java keyword as an identifier. Table 1-1 lists all of the Java keywords including one new one for 5.0, enum.
  • Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.

Examples of legal and illegal identifiers follow, first some legal identifiers:

int _a;

int $c;

int ______2_w;

int _$;

int this_is_a_very_detailed_name_for_an_identifier;

The following are illegal (it's your job to recognize why):

int :b;

int -d;

int e#;

int .f;

int 7g;

Complete List of Java Keywords

Java Keywords

Sun's Java Code Conventions

Sun estimates that over the lifetime of a standard piece of code, 20 percent of the effort will go into the original creation and testing of the code, and 80 percent of the effort will go into the subsequent maintenance and enhancement of the code. Agreeing on, and coding to, a set of code standards helps to reduce the effort involved in testing, maintaining, and enhancing any piece of code. Sun has created a set of coding standards for Java, and published those standards in a document cleverly titled "Java Code Conventions," which you can find at java.sun.com. It's a great document, short and easy to read and we recommend it highly. That said, you'll find that many of the questions in the exam don't follow the code conventions, because of the limitations in the test engine that is used to deliver the exam internationally. One of the great things about the Sun certifications is that the exams are administered uniformly throughout the world. In order to achieve that, the code listings that you'll see in the real exam are often quite cramped, and do not follow Sun's code standards. In order to toughen you up for the exam, we'll often present code listings that have a similarly cramped look and feel, often indenting our code only two spaces as opposed to the Sun standard of four. We'll also jam our curly braces together unnaturally, and sometimes put several statements on the same line…ouch! For example:

1. class Wombat implements Runnable {

2. private int i;

3. public synchronized void run() {

4. if (i%5 != 0) { i++; }

5. for(int x=0; x<5; x++, i++)

6. { if (x > 1) Thread.yield(); }

7. System.out.print(i + " ");

8. }

9. public static void main(String[] args) {

10. Wombat n = new Wombat();

11. for(int x=100; x>0; --x) { new Thread(n).start(); }

12. } }

Consider yourself forewarned—you'll see lots of code listings, mock questions, and real exam questions that are this sick and twisted. Nobody wants you to write your code like this. Not your employer, not your coworkers, not us, not Sun, and not the exam creation team! Code like this was created only so that complex concepts could be tested within a universal testing tool. The one standard that is followed as much as possible in the real exam are the naming standards. Here are the naming standards that Sun recommends, and that we use in the exam and in most of the book:

  • Classes and interfaces The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase (a format that's sometimes called "camelCase"). For classes, the names should typically be nouns. For example:

Dog

Account

PrintWriter

For interfaces, the names should typically be adjectives like

Runnable

Serializable

  • Methods The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs. For example:

getBalance

doCalculation

setCustomerName

  • Variables Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us. Some examples:

buttonWidth

accountBalance

myString

  • Constants Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators:

MIN_HEIGHT

 


 

JavaBeans Standards

The JavaBeans spec is intended to help Java developers create Java components that can be easily used by other Java developers in a visual Integrated Development Environment (IDE) tool (like Eclipse or NetBeans). As a Java programmer, you want to be able to use components from the Java API, but it would be great if you could also buy the Java component you want from "Beans 'R Us," that software company down the street. And once you've found the components, you'd like to be able to access them through a development tool in such a way that you don't have to write all your code from scratch. By using naming rules, the JavaBeans spec helps guarantee that tools can recognize and use components built by different developers.

First, JavaBeans are Java classes that have properties. For our purposes, think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods. The JavaBean naming rules that you'll need to know for the exam are the following:

JavaBean Property Naming Rules

  • If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter name for a property named "size." Keep in mind that you do not need to have a variable named size (although some IDEs expect it). The name of the property is inferred from the getters and setters, not through any variables in your class. What you return from getSize() is up to you.
  • If the property is a boolean, the getter method's prefix is either get or is. For example, getStopped() or isStopped() are both valid JavaBeans names for a boolean property.
  • The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size.
  • To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then append it to the appropriate prefix (get, is, or set).
  • Setter method signatures must be marked public, with a void return type and an argument that represents the property type.
  • Getter method signatures must be marked public, take no arguments, and have a return type that matches the argument type of the setter method for that property.

Second, the JavaBean spec supports events, which allow components to notify each other when something happens. The event model is often used in GUI applications when an event like a mouse click is multicast to many other objects that may have things to do when the mouse click occurs. The objects that receive the information that an event occurred are called listeners. For the exam, you need to know that the methods that are used to add or remove listeners from an event must also follow JavaBean naming standards:

JavaBean Listener Naming Rules

  • Listener method names used to "register" a listener with an event source must use the prefix add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source will have to allow others to register for Action events.
  • Listener method names used to remove ("unregister") a listener must use the prefix remove, followed by the listener type (using the same rules as the registration add method).
  • The type of listener to be added or removed must be passed as the argument to the method.

Examples of valid JavaBean method signatures are

public void setMyValue(int v)

public int getMyValue()

public boolean isMyStatus()

public void addMyListener(MyListener m)

public void removeMyListener(MyListener m)

Examples of invalid JavaBean method signatures are

void setCustomerName(String s) // must be public

public void modifyMyValue(int v) // can't use 'modify'

public void addXListener(MyListener m) // listener type mismatch





Class , Object , State , instance variable , behavior , method , Identifier , Keyword , Inheritance , interface , finding other class , Identifiers & JavaBeans , Identifiers and JavaBeans , Identifiers , JavaBeans , Legal Identifiers , Sun Java Code convention , sun java , code convention , JavaBeans Naming Standards , Naming Standards , java keywords , keywords , Classes and interfaces , Methods , Variables , Constants , javabean standards , JavaBean Property Naming Rules , JavaBean Listener Naming Rules , Class java , Object java , State java , instance variable java , behavior java , method java , Identifier java , Keyword java , Inheritance java , interface java , finding other class java , Identifiers & JavaBeans java , Identifiers and JavaBeans java , Identifiers java , JavaBeans java , Legal Identifiers java , Sun Java Code convention java , sun java java , code convention java , JavaBeans Naming Standards java , Naming Standards java , java keywords java , keywords java , Classes and interfaces java , Methods java , Variables java , Constants java , javabean standards java , JavaBean Property Naming Rules java , JavaBean Listener Naming Rules java , Class in java , Object in java , State in java , instance variable in java , behavior in java , method in java , Identifier in java , Keyword in java , Inheritance in java , interface in java , finding other class in java , Identifiers & JavaBeans in java , Identifiers and JavaBeans in java , Identifiers in java , JavaBeans in java , Legal Identifiers in java , Sun Java Code convention in java , sun java in java , code convention in java , JavaBeans Naming Standards in java , Naming Standards in java , java keywords in java , keywords in java , Classes and interfaces in java , Methods in java , Variables in java , Constants in java , javabean standards in java , JavaBean Property Naming Rules in java , JavaBean Listener Naming Rules in java , java Class , java Object , java State , java instance variable , java behavior , java method , java Identifier , java Keyword , java Inheritance , java interface , java finding other class , java Identifiers & JavaBeans , java Identifiers and JavaBeans , java Identifiers , java JavaBeans , java Legal Identifiers , java Sun Java Code convention , java sun java , java code convention , java JavaBeans Naming Standards , java Naming Standards , java java keywords , java keywords , java Classes and interfaces , java Methods , java Variables , java Constants , java javabean standards , java JavaBean Property Naming Rules , java JavaBean Listener Naming Rules ,




blog comments powered by Disqus