Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Chapter 1: naming conventions and basics naming conventions and basics, Lecture notes of Computer Science

Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter 1: naming conventions and basics naming conventions and basics Java Chapter

Typology: Lecture notes

2022/2023

Uploaded on 05/18/2023

chadha-essid
chadha-essid 🇮🇳

1 document

1 / 80

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CertPrs8/Java 5 Cert. Study Guide/Sierra-Bates/225360-6/Chapter 1
Blind Folio 1
1
Declarations and
Access Control
CERTIFICATION OBJECTIVES
l Declare Classes & Interfaces
l Develop Interfaces &
Abstract Classes
l Use Primitives, Arrays, Enums, &
Legal Identifiers
l Use Static Methods, JavaBeans
Naming, & Var-Args
3 Two-Minute Drill
Q&A Self Test
ch1-1123f.indd 1 11/28/05 12:24:13 AM
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50

Partial preview of the text

Download Java Chapter 1: naming conventions and basics naming conventions and basics and more Lecture notes Computer Science in PDF only on Docsity!

Declarations and

Access Control

CERTIFICATION OBJECTIVES

l Declare Classes & Interfaces

l Develop Interfaces & Abstract Classes

l Use Primitives, Arrays, Enums, & Legal Identifiers

l Use Static Methods, JavaBeans Naming, & Var-Args

3 Two-Minute Drill Q&A Self Test

 Chapter 1:^ Declarations and Access Control

W

e assume that because you're planning on becoming certified, you already know the basics of Java. If you're completely new to the language, this chapter—and the rest of the book—will be confusing; so be sure you know at least the basics of the language before diving into this book. That said, we're starting with a brief, high-level refresher to put you back in the Java mood, in case you've been away for awhile.

Java Refresher

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.

n Class A template that describes the kinds of state and behavior that objects of its type support.

n 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.

n 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.

n Behavior ( methods ) When a programmer creates a class, she creates meth- ods 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 ,

way to manage naming of, and access to, classes they need. The exam covers a lot of concepts related to packages and class access; we'll explore the details in this—and later—chapters.

CERTIFICATION OBJECTIVE

Identifiers & JavaBeans (Objectives 1.3 and 1.4)

1.3 Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

1.4 Develop code that declares both static and non-static methods, and—if appropriate— use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list.

Remember that when we list one or more Certification Objectives in the book, as we just did, it means that the following section covers at least some part of that objective. Some objectives will be covered in several different chapters, so you'll see the same objective in more than one place in the book. For example, this section covers declarations, identifiers, and JavaBeans naming, but using the things you declare is covered primarily in later chapters. So, we'll start with Java identifiers. The three aspects of Java identifiers that we cover here are

n Legal Identifiers The rules the compiler uses to determine whether a name is legal. n 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. You won't be asked questions about the Java Code Conven- tions, but we strongly recommend that programmers use them. n JavaBeans Naming Standards The naming requirements of the JavaBeans specification. You don't need to study the JavaBeans spec for the exam, but you do need to know a few basic JavaBeans naming rules we cover in this chapter.

 Chapter 1:^ Declarations and Access Control

Legal Identifiers

Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores). The exam doesn't dive into the details of which ranges of the Unicode character set are considered to qualify as letters and digits. So, for example, you won't need to know that Tibetan digits range from \u0420 to \u0f29. Here are the rules you do need to know:

n Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number! n After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. n In practice, there is no limit to the number of characters an identifier can contain. n 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. n 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;

Legal Identifiers (Exam Objectives 1.3 and 1.4) (^) 

  1. { if (x > 1) Thread.yield(); }
  2. System.out.print(i + " ");
  3. }
  4. public static void main(String[] args) {
  5. Wombat n = new Wombat();
  6. for(int x=100; x>0; --x) { new Thread(n).start(); }
  7. } }

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:

n 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

n 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

Sun’s Java Code Conventions (Exam Objectives 1.3 and 1.4) (^) 

n 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

n 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. The JavaBeans API is quite involved, but you'll need to study only a few basics for the exam. 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

n 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

 Chapter 1:^ Declarations and Access Control

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

CERTIFICATION OBJECTIVE

Declare Classes (Exam Objective 1.1)

1.1 Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

10 Chapter 1:^ Declarations and Access Control

The objective says you have to know legal identifiers only for variable names, but the rules are the same for ALL Java components. So remember that a legal identifier for a variable is also a legal identifier for a method or a class. However, you need to distinguish between legal identifiers and naming conventions, such as the JavaBeans standards, that indicate how a Java component should be named. In other words, you must be able to recognize that an identifier is legal even if it doesn’t conform to naming standards. If the exam question is asking about naming conventions—not just whether an identifier will compile—JavaBeans will be mentioned explicitly.

When you write code in Java, you're writing classes or interfaces. Within those classes, as you know, are variables and methods (plus a few other things). How you declare your classes, methods, and variables dramatically affects your code's behavior. For example, a public method can be accessed from code running anywhere in your application. Mark that method private, though, and it vanishes from everyone's radar (except the class in which it was declared). For this objective, we'll study the ways in which you can declare and modify (or not) a class. You'll find that we cover modifiers in an extreme level of detail, and though we know you're already familiar with them, we're starting from the very beginning. Most Java programmers think they know how all the modifiers work, but on closer study often find out that they don't (at least not to the degree needed for the exam). Subtle distinctions are everywhere, so you need to be absolutely certain you're completely solid on everything in this section's objectives before taking the exam.

Source File Declaration Rules

Before we dig into class declarations, let's do a quick review of the rules associated with declaring classes, import statements, and package statements in a source file:

n There can be only one public class per source code file. n Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here. n If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java. n If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present. n If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file. n import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports. n A file can have more than one nonpublic class.

Source File Declaration Rules (Exam Objective 1.1) (^) 11

not been declared in any explicit package, and are in the classpath, you won't have any way to tell the compiler or JVM which of the three you're trying to reference. Sun recommends that developers use reverse domain names, appended with division and/or project names. For example, if your domain name is geeksanonymous.com , and you're working on the client code for the TwelvePointOSteps program, you would name your package something like com.geeksanonymous.steps.client .That would essentially change the name of your class to com.geeksanonymous.steps.client.Utilities. You might still have name collisions within your company, if you don't come up with your own naming schemes, but you're guaranteed not to collide with classes developed outside your company (assuming they follow Sun's naming convention, and if they don't, well, Really Bad Things could happen).

Class Access

What does it mean to access a class? When we say code from one class (class A) has access to another class (class B), it means class A can do one of three things:

n Create an instance of class B. n Extend class B (in other words, become a subclass of class B). n Access certain methods and variables within class B, depending on the access control of those methods and variables.

In effect, access means visibility. If class A can't see class B, the access level of the methods and variables within class B won't matter; class A won't have any way to access those methods and variables.

Default Access A class with default access has no modifier preceding it in the

declaration! It's the access control you get when you don't type a modifier in the class declaration. Think of default access as package -level access, because a class with default access can be seen only by classes within the same package. For example, if class A and class B are in different packages, and class A has default access, class B won't be able to create an instance of class A, or even declare a variable or return type of class A. In fact, class B has to pretend that class A doesn't even exist, or the compiler will complain. Look at the following source file:

Class Declarations and Modifiers (Exam Objective 1.1) (^) 1 

package cert; class Beverage { }

Now look at the second source file:

package exam.stuff; import cert.Beverage; class Tea extends Beverage { }

As you can see, the superclass (Beverage) is in a different package from the subclass (Tea). The import statement at the top of the Tea file is trying (fingers crossed) to import the Beverage class. The Beverage file compiles fine, but when we try to compile the Tea file we get something like:

Can't access class cert.Beverage. Class or interface must be public, in same package, or an accessible member class. import cert.Beverage;

Tea won't compile because its superclass, Beverage, has default access and is in a different package. Apart from using fully qualified class names, which we'll cover in Chapter 10, you can do one of two things to make this work. You could put both classes in the same package, or you could declare Beverage as public, as the next section describes. When you see a question with complex logic, be sure to look at the access modifiers first. That way, if you spot an access violation (for example, a class in package A trying to access a default class in package B), you'll know the code won't compile so you don't have to bother working through the logic. It's not as if you don't have anything better to do with your time while taking the exam. Just choose the "Compilation fails" answer and zoom on to the next question.

Public Access A class declaration with the public keyword gives all classes

from all packages access to the public class. In other words, all classes in the Java Universe (JU) have access to a public class. Don't forget, though, that if a public class you're trying to use is in a different package from the class you're writing, you'll still need to import the public class. In the example from the preceding section, we may not want to place the subclass in the same package as the superclass. To make the code work, we need to add the keyword public in front of the superclass (Beverage) declaration, as follows:

1  Chapter 1:^ Declarations and Access Control

programmers were free to extend the String class (and thus substitute their new String subclass instances where java.lang.String instances are expected), civilization—as we know it—could collapse. So use final for safety, but only when you're certain that your final class has indeed said all that ever needs to be said in its methods. Marking a class final means, in essence, your class can't ever be improved upon, or even specialized, by another programmer. A benefit of having nonfinal classes is this scenario: Imagine you find a problem with a method in a class you're using, but you don't have the source code. So you can't modify the source to improve the method, but you can extend the class and override the method in your new subclass, and substitute the subclass everywhere the original superclass is expected. If the class is final, though, then you're stuck. Let's modify our Beverage example by placing the keyword final in the declaration:

package cert; public final class Beverage { public void importantMethod() { } }

Now, if we try to compile the Tea subclass:

package exam.stuff; import cert.Beverage; class Tea extends Beverage { }

We get an error something like

Can't subclass final classes: class cert.Beverage class Tea extends Beverage{ 1 error

In practice, you'll almost never make a final class. A final class obliterates a key benefit of OO—extensibility. So unless you have a serious safety or security issue, assume that some day another programmer will need to extend your class. If you don't, the next programmer forced to maintain your code will hunt you down and .

Abstract Classes An abstract class can never be instantiated. Its sole

purpose, mission in life, raison d'être, is to be extended (subclassed). (Note, how- ever, that you can compile and execute an abstract class, as long as you don't try

1  Chapter 1:^ Declarations and Access Control

Class Declarations and Modifiers (Exam Objective 1.1) (^) 1 

to make an instance of it.) Why make a class if you can't make objects out of it? Because the class might be just too, well, abstract. For example, imagine you have a class Car that has generic methods common to all vehicles. But you don't want anyone actually creating a generic, abstract Car object. How would they initialize its state? What color would it be? How many seats? Horsepower? All-wheel drive? Or more importantly, how would it behave? In other words, how would the methods be implemented?

No, you need programmers to instantiate actual car types such as BMWBoxster and SubaruOutback. We'll bet the Boxster owner will tell you his car does things the Subaru can do "only in its dreams." Take a look at the following abstract class:

abstract class Car { private double price; private String model; private String year; public abstract void goFast(); public abstract void goUpHill(); public abstract void impressNeighbors(); // Additional, important, and serious code goes here }

The preceding code will compile fine. However, if you try to instantiate a Car in another body of code, you'll get a compiler error something like this:

AnotherClass.java:7: class Car is an abstract class. It can't be instantiated. Car x = new Car(); 1 error

Notice that the methods marked abstract end in a semicolon rather than curly braces. Look for questions with a method declaration that ends with a semicolon, rather than curly braces. If the method is in a class—as opposed to an interface—then both the method and the class must be marked abstract. You might get a question that asks how you could fix a code sample that includes a method ending in a semicolon, but without an abstract modifier on the class or method. In that case, you could either mark the method and class abstract, or change the semicolon to code (like a curly brace pair). Remember, if you change a method from abstract to nonabstract, don't forget to change the semicolon at the end of the method declaration into a curly brace pair!

  1. Create a directory called food off the directory in your class path setting.
  2. Attempt to compile the two files. If you want to use the Apple class, make sure you place the Fruit.class file in the food subdirectory.

CERTIFICATION OBJECTIVE

Declare Interfaces (Exam Objectives 1.1 and 1.2)

1.1 Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

1.2 Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class.

Declaring an Interface

When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. An interface is a contract. You could write an interface Bounceable, for example, that says in effect, "This is the Bounceable interface. Any class type that implements this interface must agree to write the code for the bounce() and setBounceFactor() methods." By defining an interface for Bounceable, any class that wants to be treated as a Bounceable thing can simply implement the Bounceable interface and provide code for the interface's two methods. Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic. For example, you might want both a Ball and a Tire to have bounce behavior, but Ball and Tire don't share any inheritance relationship; Ball extends Toy while Tire extends only java.lang.Object. But by making both Ball and Tire implement Bounceable, you're saying that Ball and Tire can be treated as, "Things that can bounce," which in Java translates to "Things on which you can invoke the

Declaring an Interface (Exam Objectives 1.1 and 1.2) (^) 1 

bounce() and setBounceFactor() methods." Figure 1-1 illustrates the relationship between interfaces and classes.

FIGURE 1-

The Relationship between interfaces and classes

Think of an interface as a 100-percent abstract class. Like an abstract class, an interface defines abstract methods that take the following form:

abstract void bounce(); // Ends with a semicolon rather than // curly braces

But while an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods. Another way interfaces differ from abstract classes is that interfaces have very little flexibility in how the methods and variables defined in the interface are declared. These rules are strict:

n All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract. n All variables defined in an interface must be public, static, and final— in other words, interfaces can declare only constants, not instance variables.

 0 Chapter 1:^ Declarations and Access Control