Programming with Java: Public Classes and Default-Access Classes in Your Android App - dummies

Programming with Java: Public Classes and Default-Access Classes in Your Android App

By Barry A. Burd

A good chunk of code in your Android app will likely begin with the word public. When a class is public, any program in any package can use the code (or at least some of the code) inside that class. If a class isn’t public, then for a program to use the code inside that class, the program must be inside the same package as the class.

What Is a Paragraph?

package com.allyourcode.wordprocessor;

class Paragraph {

int alignment;

int borders;

double leftIndent;

double lineSpacing;

int style;

}

Making a Paragraph with Code in the Same Package

package com.allyourcode.wordprocessor;

class MakeAParagraph {

Paragraph paragraph = new Paragraph();

{

paragraph.leftIndent = 1.5;

}

}

Making a Paragraph with Code in Another Package

// THIS IS BAD CODE:

package com.allyourcode.editor;

import com.allyourcode.wordprocessor.Paragraph;

public class MakeAnotherParagraph {

Paragraph paragraph = new Paragraph();

{

paragraph.leftIndent = 1.5;

}

}

The Paragraph class in the first set of code has default access — that is, the Paragraph class isn’t public. The code in the second set of code is in the same package as the Paragraph class (the com.allyourcode.wordprocessor package). So you can declare an object to be of type Paragraph, and you can refer to that object’s leftIndent field.

The code in the last set isn’t in the same com.allyourcode.wordprocessor package. For that reason, the use of names like Paragraph and leftIndent aren’t legal, even if they are in the same Android Studio project. When you type the code from all of the sets above into the Android Studio editor, you see a red, blotchy mess for the last set.

java-programming-for-android-developers-2e-errors-in-code
Errors in the code.

Have you ever seen an assignment statement that’s not inside of a method? Outside of a method, you can’t assign values to things unless you create an initializer block. Like any other kind of block, an initializer block has open and close curly braces. Between the braces, the initializer block has statements that assign values to things.

In the second set of code, an initializer block assigns the value 1.5 to a paragraph’s leftIndent field. In the last set of code, an initializer block tries to assign a value, but the assignment doesn’t work because the Paragraph class isn’t public.

The .java file containing a public class must have the same name as the public class. Even the capitalization of the filename must be the same as the public class’s name.

Because of the file-naming rule, you can’t declare more than one public class in a .java file.