OCJP Chapter 1-1
Transcript of OCJP Chapter 1-1
-
7/31/2019 OCJP Chapter 1-1
1/89
Declarations & AccessControls Identifiers & JavaBeans
Legal Identifiers
Sun's Java Code Conventions
JavaBeans Standards
Declare Classes
Source File Declaration Rules
Class Declarations and Modifiers
Declare Interfaces Declaring an Interface
Declaring Interface Constants
Declare Class Members
Access Modifiers
Nonaccess Member Modifiers
Constructor Declarations
Variable Declarations
Declaring Enums
Two-Minute Drill
Self Test With Answers
-
7/31/2019 OCJP Chapter 1-1
2/89
-
7/31/2019 OCJP Chapter 1-1
3/89
Identifiers - Brain Teaser
int 7g; int _a; int $c; int :b; int ______2_w; int -d; int _$; int e#; int
this_is_a_very_detailed_name_for_an_identifier;
int .f;
-
7/31/2019 OCJP Chapter 1-1
4/89
Identifiers Java Keywords
-
7/31/2019 OCJP Chapter 1-1
5/89
-
7/31/2019 OCJP Chapter 1-1
6/89
Declaration Rules A source code file can have only one public class. If the source file contains a public class, the filename must match
the public class name.
A file can have only one package statement, but multiple imports.
The package statement (if any) must be the first (non-comment) line
in a source file. The import statements (if any) must come after the package and
before
the class declaration.
If there is no package statement, import statements must be the first
(non comment) statements in the source file. package and import statements apply to all classes in the file.
A file can have more than one nonpublic class.
Files with no public classes have no naming restrictions
-
7/31/2019 OCJP Chapter 1-1
7/89
Class Access (visibility)Modifiers There are three access modifiers: public, protected, and
private.
There are four access levels: public, protected, default, andprivate.
Classes can have only public or default access.
A class with default access can be seen only by classeswithin the same package.
A class with public access can be seen by all classes from allpackages.
Class visibility revolves around whether code in one class can Create an instance of another class
Extend (or subclass), another class
Access methods and variables of another class
-
7/31/2019 OCJP Chapter 1-1
8/89
Class Access (visibility)Modifierspackage cert;class Beverage { }
Now look at the second source file:
package exam.stuff;
import cert.Beverage;
class Tea extends Beverage { }
Can't access class cert.Beverage. Class or interface must be public, in samepackage, or an accessible member class. import cert.Beverage;
package cert;
Public class Beverage { }
This changes the Beverage class so it will be visible to all classes in allpackages.
The class can now be instantiated from all other classes, and any class is nowfree to
-
7/31/2019 OCJP Chapter 1-1
9/89
Class Modifiers(Nonaccess) Classes can also be modified with final, abstract, or strictfp. A class cannot be both final and abstract.
A final class cannot be subclassed.
An abstract class cannot be instantiated.
A single abstract method in a class means the whole classmust be abstract
methods marked abstract end in a semicolon rather than curlybraces.
An abstract class can have both abstract and nonabstract
methods. The first concrete class to extend an abstract class must
implement all of its
abstract methods.
-
7/31/2019 OCJP Chapter 1-1
10/89
Class Modifiers (Nonaccess) Final Classpackage 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 { }
Can't subclass final classes: class cert.Beverage class Tea extendsBeverage{
-
7/31/2019 OCJP Chapter 1-1
11/89
Class Modifiers (Nonaccess) Abstract Classabstract class Car {
private double price;
private String model;
private String year;
public abstract void goFast();
public abstractvoid 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
-
7/31/2019 OCJP Chapter 1-1
12/89
Interface Implementation
Interfaces are contracts for what a class can do, but they say nothing about the way in which the class must do it.
Interfaces can be implemented by any class, from any inheritance tree.
An interface is like a 100-percent abstract class, and is implicitly abstractwhether you type the abstract modifier in the declaration or not.
An interface can have only abstract methods, no concrete methods allowed. Interface methods are by default public and abstractexplicit declaration
of these modifiers is optional.
Interfaces can have constants, which are always implicitly public, static, andfinal.
Interface constant declarations of public, static, and final are optional
in any combination.
A legal nonabstract implementing class has the following properties:
It provides concrete implementations for the interface's methods.
It must follow all legal override rules for the methods it implements.
It must follow all legal override rules for the methods it implements.
It must not declare any new checked exceptions for an
-
7/31/2019 OCJP Chapter 1-1
13/89
Interface Implementation
It may declare runtime exceptions on any interface methodimplementation regardless of the interface declaration.
It must maintain the exact signature (allowing for covariant returns)
and return type of the methods it implements (but does not have to
declare the exceptions of the interface).
A class implementing an interface can itself be abstract. An abstract implementing class does not have to implement the interface
methods (but the first concrete subclass must).
A class can extend only one class (no multiple inheritance), but it can
implement many interfaces.
Interfaces can extend one or more other interfaces. Interfaces cannot extend a class, or implement a class or interface.
When taking the exam, verify that interface and class declarations are legal
before verifying other code logic.
-
7/31/2019 OCJP Chapter 1-1
14/89
-
7/31/2019 OCJP Chapter 1-1
15/89
Interface Implementation
-
7/31/2019 OCJP Chapter 1-1
16/89
Interface Implementation
Compilation Error : BAR is a constant (public static final). Youcannot change the value of a constant
-
7/31/2019 OCJP Chapter 1-1
17/89
Member Access Modifiers
Methods and instance (nonlocal) variables are known as "members. Members can use all four access levels: public, protected, default, private.
Member access comes in two forms:
Code in one class can access a member of another class.
A subclass can inherit a member of its superclass.
If a class cannot be accessed, its members cannot be accessed.
Determine class visibility before determining member visibility.
public members can be accessed by all other classes, even in otherpackages.
If a superclass member is public, the subclass inherits itregardless ofpackage.
Members accessed without the dot operator (.) must belong to the sameclass.
this. always refers to the currently executing object.
this.aMethod() is the same as just invoking aMethod().
private members can be accessed only by code in the same class.
private members are not visible to subclasses, so private members cannotbe inherited.
-
7/31/2019 OCJP Chapter 1-1
18/89
Member Access Modifiers
Default and protected members differ only when subclasses are involved: Default members can be accessed only by classes in the same package.
protected members can be accessed by other classes in the same
package, plus subclasses regardless of package.
protected = package plus kids (kids meaning subclasses).
For subclasses outside the package, the protected member can beaccessed only through inheritance; a subclass outside the package cannot
access a protected member by using a reference to a superclass instance
(in other words, inheritance is the only mechanism for a subclass
outside the package to access a protected member of its superclass).
A protected member inherited by a subclass from another package isnot accessible to any other class in the subclass package, except for the
subclass' own subclasses.
-
7/31/2019 OCJP Chapter 1-1
19/89
Member Access Modifiers
-
7/31/2019 OCJP Chapter 1-1
20/89
Member Access Modifiers
-
7/31/2019 OCJP Chapter 1-1
21/89
-
7/31/2019 OCJP Chapter 1-1
22/89
Member Access Modifiers Public Access
-
7/31/2019 OCJP Chapter 1-1
23/89
Member Access Modifiers Private
-
7/31/2019 OCJP Chapter 1-1
24/89
Member Access Modifiers Public &Private
-
7/31/2019 OCJP Chapter 1-1
25/89
Member Access Modifiers Default Access
-
7/31/2019 OCJP Chapter 1-1
26/89
Member Access Modifiers Protected Access
-
7/31/2019 OCJP Chapter 1-1
27/89
Member Access Modifiers Protected Access
-
7/31/2019 OCJP Chapter 1-1
28/89
Member Access Modifiers Protected & DefaultAccess
-
7/31/2019 OCJP Chapter 1-1
29/89
Local Variables
Local (method, automatic, or stack) variable declarations cannot have accessmodifiers.
final is the only modifier available to local variables.
Local variables don't get default values, so they must be initialized beforeuse.
The code below will not compile
-
7/31/2019 OCJP Chapter 1-1
30/89
Member Access Modifiers
-
7/31/2019 OCJP Chapter 1-1
31/89
-
7/31/2019 OCJP Chapter 1-1
32/89
Non-Access Member Modifiers
Synchronized methods can have any access control and canalso be
marked final.
abstract methods must be implemented by a subclass, sothey must be inheritable. For that reason:
abstract methods cannot be private.
abstract methods cannot be final.
The native modifier applies only to methods.
The strictfp modifier applies only to classes and methods.
-
7/31/2019 OCJP Chapter 1-1
33/89
Non-Access Member Modifiers Final Methods
-
7/31/2019 OCJP Chapter 1-1
34/89
Non-Access Member Modifiers Final Arguments
-
7/31/2019 OCJP Chapter 1-1
35/89
Non-Access Member Modifiers Abstract Methods
-
7/31/2019 OCJP Chapter 1-1
36/89
-
7/31/2019 OCJP Chapter 1-1
37/89
Non-Access Member Modifiers Abstract Methods
-
7/31/2019 OCJP Chapter 1-1
38/89
Non-Access Member Modifiers Synchronized & Native Methods
Synchronized methods can be accessed by only one threadat a time
Can be paired with private, public, default and protected
Native methods are implemented in platform dependent code(like C)
native keyword can be applied only to methods. It cannot beapplied to classes or variables.
Native method does not have body. They are like abstractmethods. No Implementation
-
7/31/2019 OCJP Chapter 1-1
39/89
Non-Access Member Modifiers Strictfp Methods
Strictfp forces floating point operations to adhere to IEEE 754standard
With Strictfp you can predict how your floating points willbehave regardless of underlying platform in which JVM isrunning on
Downside If underlying platform supports greater precision,Strictfp would not be able to take advantage of it
Strictfp can be applied only to Classes and Methods.
Variables cannot be marked Strictfp.
-
7/31/2019 OCJP Chapter 1-1
40/89
var-args Methods
As of Java 5, methods can declare a parameter that acceptsfrom zero to many arguments, a so-called var-arg method.
A var-arg parameter is declared with the syntax type... name;for instance:
doStuff(int... x) { }
A var-arg method can have only one var-arg parameter.
doStuff(int... X, float Y) { } // Will not compile
In methods with normal parameters and a var-arg, the var-argmust come last.
doStuff(int... X, float Y) { } // Will not compiledoStuff(int X, float Y) { } // Will compile
-
7/31/2019 OCJP Chapter 1-1
41/89
var-args Methods
-
7/31/2019 OCJP Chapter 1-1
42/89
-
7/31/2019 OCJP Chapter 1-1
43/89
Variable Declaration Instance variables can
Have any access control
Be marked final or transient
Instance variables can't be abstract, synchronized, native, orstrictfp.
It is legal to declare a local variable with the same name as
an instance variable; this is called "shadowing. final variables have the following properties:
final variables cannot be reinitialized once assigned a value.
final reference variables cannot refer to a different object once the
object has been assigned to the final variable.
final reference variables must be initialized before the constructorcompletes.
There is no such thing as a final object. An object referencemarked final does not mean the object itself is immutable.
The transient modifier applies only to instance variables.
The volatile modifier applies only to instance variables
-
7/31/2019 OCJP Chapter 1-1
44/89
Variable Declaration Primitives (Ranges)
-
7/31/2019 OCJP Chapter 1-1
45/89
Variable Declaration
V i bl D l ti L l
-
7/31/2019 OCJP Chapter 1-1
46/89
Variable Declaration Local(Automatic/Stack/Method) Variables
Local variables cannot be marked public, private, default orprotected.
They cannot be marked static, transient, volatile, abstract.
final is the only modifier that can be used
Local variables dont get default values. Only instance
variables get default values if not initialized. Local variablesmust be initialized before it can be used.
-
7/31/2019 OCJP Chapter 1-1
47/89
-
7/31/2019 OCJP Chapter 1-1
48/89
A D l ti
-
7/31/2019 OCJP Chapter 1-1
49/89
Array Declaration
Arrays can hold primitives or objects, but the array itself isalways an object.
When you declare an array, the brackets can be to the left orright of the variable name.
It is never legal to include the size of an array in thedeclaration.
An array of objects can hold any object that passes the IS-A(or instanceof) test for the declared type of the array. Forexample, if Horse extends Animal, then a Horse object can gointo an Animal array.
// Code above wont compil
Static Variables & Methods
-
7/31/2019 OCJP Chapter 1-1
50/89
Static Variables & Methods They are not tied to any particular instance of a class.
No classes instances are needed in order to use staticmembers of the class.
There is only one copy of a static variable / class and allinstances share it.
static methods do not have direct access to non-staticmembers.
enums
-
7/31/2019 OCJP Chapter 1-1
51/89
enums An enum specifies a list of constant values assigned to a type.
An enum is NOT a String or an int; an enum constant's type is theenum type. For example, SUMMER and FALL are of the enum type
Season. An enum can be declared outside or inside a class, but NOT in a
method.
An enum declared outside a class must NOT be marked static, final,abstract, protected, or private.
Enums can contain constructors, methods, variables, and constantclass bodies.
enum constants can send arguments to the enum constructor, usingthe syntax BIG(8), where the int literal 8 is passed to the enumconstructor.
enum constructors can have arguments, and can be overloaded.
enum constructors can NEVER be invoked directly in code. They arealways called automatically when an enum is initialized.
The semicolon at the end of an enum declaration is optional. Theseare legal:
enum Foo { ONE, TWO, THREE}
enum Foo { ONE, TWO, THREE} ;
enums
-
7/31/2019 OCJP Chapter 1-1
52/89
enums As of Java 5.0, you can restrict a variable to having one of only a
few pre-defined values
enums
-
7/31/2019 OCJP Chapter 1-1
53/89
enums
enums
-
7/31/2019 OCJP Chapter 1-1
54/89
enums
enums
-
7/31/2019 OCJP Chapter 1-1
55/89
enums
Test
-
7/31/2019 OCJP Chapter 1-1
56/89
Test
Test
-
7/31/2019 OCJP Chapter 1-1
57/89
Test
Test
-
7/31/2019 OCJP Chapter 1-1
58/89
Test
Test
-
7/31/2019 OCJP Chapter 1-1
59/89
Test
Test
-
7/31/2019 OCJP Chapter 1-1
60/89
Test
Test
-
7/31/2019 OCJP Chapter 1-1
61/89
Test
Test
-
7/31/2019 OCJP Chapter 1-1
62/89
est
-
7/31/2019 OCJP Chapter 1-1
63/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
64/89
y
Since enum Direction is declared inside the class Nav, it can beaccessed only using Class Nav reference
Try it Out
-
7/31/2019 OCJP Chapter 1-1
65/89
y
empID is not set anyvalue within the
constructorEmployee(String id)
Try it Out
-
7/31/2019 OCJP Chapter 1-1
66/89
y
Enum values can be assigned only by using the Dot
operator on the enum MyColor
Try it Out
-
7/31/2019 OCJP Chapter 1-1
67/89
3, 4 and 5th fragments compile successfully.
Try it Out
-
7/31/2019 OCJP Chapter 1-1
68/89
Public can be accessed by any class in any package.However class is default. Hence class can beaccessed only within test package.
Try it Out
-
7/31/2019 OCJP Chapter 1-1
69/89
At runtime what object is assigned determines whichoverridden version will be called. Remember,overriding is run time polymorphism
Try it Out
-
7/31/2019 OCJP Chapter 1-1
70/89
Salmon is defined within animal.fish package. For using the methods
in Salmon class we need to import the class
Try it Out
-
7/31/2019 OCJP Chapter 1-1
71/89
Only $, _ can be used. No other special characters are allowed
Try it Out
-
7/31/2019 OCJP Chapter 1-1
72/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
73/89
Listener naming conventions are addXXXListener,removeXXXListener
Try it Out
-
7/31/2019 OCJP Chapter 1-1
74/89
Interfaces variables (or constants) are implicitly public, static and final
Try it Out
-
7/31/2019 OCJP Chapter 1-1
75/89
Overriding method to be called is determined
during run time. Thus what object is assigned atrun time determines which method gets called
Try it Out
-
7/31/2019 OCJP Chapter 1-1
76/89
Inner class is default here. Hence only classes in the same packagecan access InnerTriangle, which has the variable base
-
7/31/2019 OCJP Chapter 1-1
77/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
78/89
Repeated question. addXXXListener and removeXXXListerner arethe naming conventions
Try it Out
-
7/31/2019 OCJP Chapter 1-1
79/89
Value of final variable cannot be changed once initialized
Try it Out
-
7/31/2019 OCJP Chapter 1-1
80/89
getText() method is default in packageA. It will not have visibility inPackage B
Try it Out
-
7/31/2019 OCJP Chapter 1-1
81/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
82/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
83/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
84/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
85/89
-
7/31/2019 OCJP Chapter 1-1
86/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
87/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
88/89
Try it Out
-
7/31/2019 OCJP Chapter 1-1
89/89