2.93k likes | 3.09k Views
Module 00: (almost) Getting Started. Objectives What Is the Java Technology? Primary Goals of the Java Technology A Basic Java Application. Agenda. Describe key features of Java Write, compile, and run a simple Java application Describe the Java virtual machine’s (JVM machine’s) function
E N D
Objectives What Is the Java Technology? Primary Goals of the Java Technology A Basic Java Application Agenda
Describe key features of Java Write, compile, and run a simple Java application Describe the Java virtual machine’s (JVM machine’s) function Define garbage collection List the three tasks performed by the Java platform that handle code security Objectives
What Is the Java Technology? Java technology is: A programming language A development environment An application environment A deployment environment
Primary Goals of the Java Technology Provides an easy-to-use language by: Avoiding many pitfalls of other languages Being object-oriented Enabling users to create streamlined and clear code Provides an interpreted environment for: Improved speed of development Code portability
Primary Goals of the Java Technology Enables users to run more than one thread of activity Loads classes dynamically; that is, at the time they are actually needed Supports dynamically changing programs during runtime by loading classes from disparate sources Furnishes better security
Primary Goals of the Java Technology The following features fulfill these goals: The JVM Garbage collection Code security
The Java Virtual Machine Provides hardware platform specifications Reads compiled byte codes that are platform independent Is implemented as software or hardware Is implemented in a Java technology development tool or a Web browser
The Java Virtual Machine The majority of type checking is done when the code is compiled. Implementation of the JVM approved by Sun Microsystems must be able to run any compliant class file.
Garbage Collection Allocated memory that is no longer needed should be deallocated In other languages, deallocation is the programmer’s responsibility The Java programming language provides a system level thread to track memory allocation Garbage collection: Checks for and frees memory no longer needed Is done automatically Can vary dramatically across JVM implementations
Code Security The Java application environment performs as follows:
The Java Runtime Environment Performs three main tasks: Loads code Verifies code Executes code
The Class Loader Loads all classes necessary for the execution of a program Maintains classes of the local file system in separate “namespaces”
The Bytecode Verifier Ensures that: The code adheres to the JVM specification The code does not violate system integrity The code causes no operand stack overflows or underflows The parameter types for all operational code are correct No illegal data conversions (the conversion of integers to pointers) have occurred
A Basic Java Application public class TestGreeting{ public static void main (String[] args) { Greeting hello = new Greeting(); hello.greet(); } } public class Greeting { public void greet() { System.out.println(“hi”); } }
Section 1: Declarations, Initialization and Scoping
Objectives • Develop code that declare 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). • 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.
Objectives • 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. • 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.
Objectives • Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method. • Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class. Go to Java!!
Declarations and Access Control Declare Classes 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).
Declarations and Access Control 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: • There can be only one public class per source code file. • 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. • 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.
Source File Declaration • 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. • 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.
Source File Declaration • 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. • A file can have more than one nonpublic class. • Files with no public classes can have a name that does not match any of the classes in the file.
Class Declarations and Modifiers The following code is a bare-bones class declaration: class MyClass { } This code compiles just fine, but you can also add modifiers before the class declaration. Modifiers fall into two categories: Access modifiers: public, protected, private. Non-access modifiers (including strictfp, final, and abstract). We'll look at access modifiers first, so you'll learn how to restrict or allow access to a class you create. Access control in Java is a little tricky because there are four access controls (levels of access) but only three access modifiers.
Class Declarations and Modifiers • The fourth access control level (called default or package access) is what you get when you don't use any of the three access modifiers. • In other words, every class, method, and instance variable you declare has an access control, whether you explicitly type one or not. • Although all four access controls (which means all three modifiers) work for most method and variable declarations, a class can be declared with only public or default access; the other two access control levels don't make sense for a class, as you'll see
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: Create an instance of class B. • Extend class B (in other words, become a subclass of class B). • 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.
Default Access 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: package cert; class Beverage { } Now look at the second source file: package exam.stuff; import cert.Beverage; class Tea extends Beverage { }
Default Access • 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. When you see a question with complex logic, be sure to look at the access modifiers first.
Default Access • 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.
Public Classes 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: package cert; public class Beverage { }
Public Access • This changes the Beverage class so it will be visible to all classes in all packages. • The class can now be instantiated from all other classes, and any class is now free to subclass (extend from) it—unless, that is, the class is also marked with the non-access modifier final.
Other (Nonaccess) Class Modifiers You can modify a class declaration using the keyword: • final • abstract • strictfp. These modifiers are in addition to whatever access control is on the class, so you could, for example, declare a class as both public and final. But you can't always mix nonaccess modifiers. You're free to use strictfp in combination with final, for example, but you must never, mark a class as both final and abstract.
Other (Nonaccess) Class Modifiers • You won't need to know how strictfp works, so we're focusing only on modifying a class as final or abstract. For the exam, you need to know only that strictfp is a keyword and can be used to modify a class or a method, but never a variable. • Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier, floating points used in the methods might behave in a platform-dependent way. • If you don't declare a class as strictfp, you can still get strictfp behavior on a method-by-method basis, by declaring a method as strictfp. If you don't know the IEEE 754 standard, now's not the time to learn it. You have, as we say, bigger fish to fry.
Final Classes When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will give you a compiler error. So why would you ever mark a class final? After all, doesn't that violate the whole object-oriented (OO) notion of inheritance? • You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. • If you're deeply dependent on the implementations of certain methods, then using final gives you the security that nobody can change the implementation out from under you.
Final Classes • You'll notice many classes in the Java core libraries are final. • For example, the string class cannot be subclassed. • Imagine the havoc if you couldn't guarantee how a string object would work on any given system your application is running on! If 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.
Final Classes 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() { } }
Final Classes 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 <insert really scary thing>.
Abstract Classes • An abstract class can never be instantiated • Its sole purpose, mission in life, is to be extended (subclassed). Note, however, that you can compile and execute an abstract class, as long as you don't try to make an instance of it.
Abstract Classes 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?
Abstract Classes 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 }
Abstract Classes 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.
Abstract Classes • 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!