Вы находитесь на странице: 1из 71

Core Java

Arrays
An array is a collection of variables of the same type. A variable declared in brackets, [], is an array reference. Three steps Declaration - tell the compiler what the name is and the type of its elements. Construction Initialization
int numbers[]; // declaration numbers = new int[100]; // construction for (int i=0; i<100; i++) { numbers[i] = i; }

String username[]; float[] balance;

Arrays
Components of an array are accessed by a simple integer index. Element indexing begins with the number 0.
username[0] = "Fred"; username[1] = "Barney";

The size of an array is easily accessed with the length attribute.


for (int i=0; i<username.length; i++) { System.out.println("The user's name is: " + username[i]); }

Indexing past the end of an array throws an exception. Multidimensional arrays can be created.
3

Extending Classes
It is easy for one Java class to extend the behavior of another Java class. This capability is usually referred to as polymorphism, which means that an object of a given class can have multiple forms.

Objectives
Extend existing classes. Define the terms subclass, superclass, overloading, and overriding. Define how constructors of subclasses operate. Define the implications of marking a class or method as final. Discuss the considerations of cloning classes.
5

An Extended Class
An extended class can be used wherever the original class was legal. Polymorphism - an object of a given class can have multiple forms. The extended class is a subclass. The class it extends is the superclass. If a class does not explicitly extend a class then it implicitly extends Object. Object declares methods that are implemented by all objects.
6

What protected really means?


A protected class member can be accessed by classes that extend that class. A protected class member also be accessed from code within the same package. A protected class member also be accessed from references of the class's type or one of it's subtypes.

Constructors in extended classes


When you extend a class, the new class must choose one of it's superclass's constructors to invoke. If you do not invoke a superclass constructor as your constructors first executable statement, the superclass no-arg constructor is automatically invoked before any statements in your new constructor are executed. If the superclass does not have a no-arg constructor, you must explicitly invoke one of the superclass's other constructors, or invoke another of your own constructors using the this construct. If you use super(), it must be the first executable statement of the constructor. The language provides a default no-arg constructor for you.

Constructors order dependencies


When an object is created, all it's fields are set to default initial values. Then the constructor is invoked.

Constructor Phases
Invoke a superclass's constructor. Initialize the fields using their initializers and any initialization blocks. Execute the body of the constructor.

10

Overriding methods, hiding fields, and nested classes


Overloading - providing more than one method with the same name but with different signatures. Overriding - replacing a superclass's implementation with your own. Overriding
Signatures must be identical. Return type must be the same. Only accessible non-static methods can be overridden. A subclass can determine whether a parameter in an overridden method is final.

The super keyword


Available in all non-static methods of a class. super.method() - uses the superclass's implementation of method.

11

Marking methods and classes final


No extended class can override the method to change its behavior. (This is the final version of that method.) A class marked final cannot be extended by any other class (and, all the methods of a final class are implicitly final). Security - anyone who uses the class can be sure the behavior will not change (validatePassword example). Serious restriction on the use of the class. Final simplifies optimizations.

12

The object class


All classes inherit from Object. Object's methods fall in two classes: utilities, and thread support. Object's utility methods
equals(Object o) hashCode() clone() getClass() finalize()

13

Anonymous classes
Use these when the weight of a full class seems too much for your needs. Extend a class or implement an interface. Defined at the same time they are created with new. Defined in the new expression. Cannot have their own constructors. Can easily become hard to read. Avoid anonymous classes longer than six lines. Use them only in the simplest of expressions.

14

Abstract Classes and methods


Helpful when some of the behavior is defined for most objects of a given type, but some behavior makes sense for only particular classes and not the superclass. Declare classes that define only part of an implementation. Each method not implemented in an abstract class is marked abstract. A class with any abstract methods must be declared abstract. Abstract methods must be implemented by subclasses that are not abstract themselves.
15

Cloning objects
A clone method returns a new object whose initial state is a copy of the current state of the object on which clone was invoked. Subsequent changes to the clone will not affect the state of the original. Object.clone() Three major considerations in writing a clone method
Empty Cloneable interface. Object.clone() method. CloneNotSupportedException.

Four different attitudes a class can have towards clone


Support clone. Conditionally support clone. Allow subclasses to support clone but don't publicly support it. Forbid clone.
16

Designing a class to be extended



Choose the access for each part of a class design carefully: public, protected, private. If your design will have subclasses, design your protected parts carefully. Bad effects of public fields
Fields can be modified at any time by a programmer. No way to add functionality.

Non-final classes have two interfaces


Public interface for programmers using the class. Protected interface for programmers extending the class.

17

Interfaces
Interfaces are a way to declare a type consisting only of abstract methods and related constants, classes, and interfaces. An interface in Java is an expression of pure design, whereas a class is a mix of design and implementation.

18

Objectives
Describe an interface. Define the differences between single and multiple inheritance. Show how to implement an interface. Describe the differences between interfaces and abstract classes.

19

More about Interface


Java has single inheritance of implementation - you can extend only one class. Java has multiple interface inheritance. All methods in an interface are implicitly abstract. Each class that implements the interface must implement all its methods. Methods in an interface are always public. Fields in an interface are always static and 20 final.

Single inheritance versus multiple inheritance


A new class can extend exactly one superclass. The new class inherits the superclass's (a) contract and (b) implementation. Some languages allow multiple inheritance - two or more superclasses. Problem of multiple inheritance arises from multiple inheritance of implementation. (Usually related to a class that maintains state information.)

21

Extending Interfaces
Interfaces can be extended using the extends keyword. Interfaces can extend more than one interface:
interface Shimmer extends FloorWax, DessertTopping {

All methods and constants defined by FloorWax and DessertTopping are part of Shimmer.

22

Interfaces Vs Abstract Classes


Two Important Differences Between Interfaces and Abstract Classes Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. Interface or Abstract Class These two differences usually direct the choice. If multiple inheritance is important or even useful interfaces are used. Abstract class lets you define some or all of the implementation. Any major class you expect to be extended should be an implementation of an interface.
23

Exceptions
Applications can run into many kinds of errors during execution. Java exceptions provide a clean way to check for errors without cluttering code, and provide a mechanism to signal errors directly. Exceptions are also part of a method's contract. An exception is thrown when an unexpected error condition is encountered. The exception is then caught be an encompassing clause further up the method invocation stack.

24

Objectives
Create their own Exception class. Throw an exception. Define the three choices you have when a method throws an exception. Use try/catch/finally to run a method that may throw an exception. Describe the purpose of the finally clause, and when it is run. Make better decisions about when to throw exceptions in your code.

25

Creating Exception Types


Exceptions are objects. Must extend the class Throwable or one of it's subclasses. By convention new exception types extend Exception (a subclass of Throwable).
public class BadPizzaException extends Exception { public String attrName; BadPizzaException(String name) { super( "BadPizzaException: " + name ); attrName = name; } }
26

throw
Exceptions are thrown using the throw statement. Exceptions are objects, so they must be created (with new) before being thrown.

27

The throws clause


The exceptions a method can throw are declared with a throws clause. The exceptions a method can throw are as important as the value type the method returns. Choices when invoking a method that has a throws clause
Catch the exception and handle it. Catch the exception and map it to one of your exceptions by throwing an exception of a type declared in your own throws clause. Declare the exception in your throws clause and let the exception pass through your method.
28

try, catch, and finally


Exceptions are caught by enclosing code in try blocks. The body of try is executed until an exception is thrown or it finishes successfully. If an exception is thrown, each catch clause is examined in turn, from first to last, to see whether the exception object is assignable tto the type declared with the catch. When an assignable catch is found, its code block is executed. No other catch clause will be executed. Any number of catch clauses can be associated with a try, as long as each clause catches a different type of exception. If a finally clause is present in the try block, the code is executed after all other processing in the try is complete. This happens no matterhow the try clause completed - normally, through an exception, or through a return or break.
29

finally
A mechanism for executing a section of code whether or not an exception is thrown. Usually used to clean up internal state or to release non-object resources, such as open files stored in local variables. Can also be used to cleanup for break, continue, and return. No way to leave a try block without executing its finally clause. A finally clause is always entered with a reason; that reason is remembered when the finally clause exits.
30

Concept of Packages
Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. In Java, the codes which can be reused by other programs is put into a Package. A Package is a collection of classes, interfaces and/or other packages. Packages are essentially a means of organizing classes together as groups.

31

Features of Packages
Packages are useful for the following purposes: Packages allow you to organize your classes into smaller units ( such as folders ) and make it easy to locate and use the appropriate class file. It helps to avoid naming conflicts. When you are working with a number of classes, it becomes difficult to decide on names of the classes & methods. At times you would want to use the same name, which belongs to an another class. Package, basically hides the classes and avoids conflicts in names. Packages allow you to protect your classes, data and methods in a larger way than on a class-to-class basis. 32 Package names can be used to identify your classes.

More on Packages
A package name should be unique. A good way to ensure unique package names is to use an Internet domain name (reversed):
package COM.missiondata.utils;

A public class or interface is accessible to code outside that package. Types that are not public have package scope; they are available to all other code in the same package, but are hidden outside the package and even from code in nested packages. Package scope is the default if public/protected/private are not declared.
33

Importing a Package
In Java, the Packages (where the required method is already created) can be imported into any program where the method is to be used. We can import a Package in the following manner : import package_name . class_name ; Suppose you wish to use a class say My_Class whose location is as follows: This class can be imported as follows :

import My_Package . MySub_Package . My_Class ;

34

Creating a Package
In Java Packages are created in the following manner : package package_name ;

35

Standard Java Packages

36

java.lang package

37

Some of the important methods of Math class


int abs(int i) - returns the absolute value of I long abs(long l) - returns the absolute value of l float abs(float f) - returns the absolute value of f double abs(double d) - returns the absolute value of d double ceil(double d) -- returns as a double the smallest integer that is not less than d double floor(double d) --- returns as a double the largest integer

38

java.io package

39

java.io package
The classes derived in Inputstream and Outputstream can only read from or write to the respective files. We cannot use the same class for both reading and writing operations. An exception to this rule is the class RandomAccessFile. This is the class used to handle files that allow random access and is capable of mixed reading and writing operations on a file. There are two additional interface to this package :
Data input Data output

These classes are used to transfer data other than bytes or characters
40

java.util package
One of the most important package in this package is the class Date, which can be used to represent or manipulate date and time information. In addition, the class also enable us to account for time zones . Java helps us to change the size of an array which is usually fixed, by making use of the class Vector. This class also enable us to add, remove and search for items in the array.

41

Tips on using packages


The statement : import java.awt.* ; Will include all the classes available in the awt subdirectory present in the java directory. While creating a package, care should be taken that the statement for creating a package must be written before any other import statements

42

Important Packages in Java


java.lang
You dont need to explicitly import this package. It is always imported for you.

java.io
This package consists of classes that help you for all the Input and Output operations.

java.applet
This package consists of classes that you need, to execute an applet in the browser or an appletviewer.

java.awt
This package is useful to create GUI applications.

java.util
This package provides a variety of classes and interfaces for creating lists, calendar, date, etc.

java.net
This package provides classes and interfaces for TCP/IP network programming.

43

IO Streams
Objectives
IO Streams in Java Understanding some fundamental streams Creating streams for required functionality Some advanced streams

44

Streams
Streams are channels of communication Provide a good abstraction between the source and destination Could also act as a shield to lower transport implementation Most of Javas IO is based on streams
Byte-oriented streams Character-oriented streams

Concatenating Streams

45

More about Streams


A stream can be thought of as a Conduit (pipe) for data between a source and the destination. Two types of Streams are:
Streams which carries bytes are called low level streams. Examples are FileInputStream and FileOutputStream.

Streams which carries primitive data types are called high level streams.
Examples are DataInputStream and DataOutputStream.

InputStreams are used for reading the data from the source. OutputStreams are used for writing the data to the 46 destination.

How it works?

47

Writing primitives to a File


Writing Primitives to a File
DataOutputStream dos = new DataOutputStream( new FileOutputStream("item.dat")); dos.writeFloat(itemPrice); dos.writeInt(itemQty); dos.writeChars(itemNo);

48

Filter Streams
Filter contents as they pass through the stream Filters can be concatenated as seen before Some filter streams
Buffered Streams LineNumberInputStream PushBackInputStream PrintStream

49

Conversion Streams
InputStreamReader: bridge from byte streams to character streams
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));

OutputStreamWriter: bridge from chararcter streams to byte streams

50

Summary of IO Streams and Readers


The java.io package provides a rich framework and class library for reading and writing any type of data (text, numbers, images) in streams from any type of location (disk, network, memory). The package provides 2 class hierarchies: one for byte streams, the other for character streams.
Base classes for reading data: InputStream for byte streams, Reader for character streams. Base classes for writing data: OutputStream for byte streams, Writer for character streams.

Example of copying one file to another.


Reader in = new FileReader("one.txt"); Writer out = new FileWriter("two.txt"); int token = -1; while( (token != in.read()) != -1 ) { out.write(token); } out.close();

51

Properties Click
// Read properties file. Properties properties = new Properties(); try { properties.load(new FileInputStream("filename.properties")); } catch (IOException e) { } // Write properties file. try { properties.store(new FileOutputStream("filename.properties"), null); } catch (IOException e) { }

52

Properties File
Sample properties file
name=Shiv job=trainner

Getting and Setting Properties


String string = properties.getProperty("name"); properties.setProperty("name", "New Shiv");

53

Using Wrappers
The wrapper classes correlate to the primitive types. Wrappers have two main functions:
To wrap primitives so that they can be handled like objects To provide utility methods for primitives (usually conversions)

Other than Character and Integer, wrapper class names are the primitives name, capitalized. Wrapper constructors can take a String or a primitive, except for Character, which can only take a char. A Boolean object cant be used like a boolean primitive. The three most important method families are
xxxValue() Takes no arguments, returns a primitive parseXxx() Takes a String, returns a primitive, is static, throws NFE valueOf() Takes a String, returns a wrapped object, is static, throws NFE
54

Assertions
Assertions give you a way to test your assumptions during development and debugging. Assertions are typically enabled during testing but disabled during deployment. You can use assert as a keyword (as of version 1.4) or an identifier, but not both together. To compile older code that uses assert as an identifier (for example, a method name), use the -source 1.3 command-line flag to javac. Assertions are disabled at runtime by default. To enable them, use a commandline flag -ea or -enableassertions. You can selectively disable assertions using the -da or -disableassertions flag. You can enable or disable assertions in the system classes with the -esa or -dsa flags. You can enable and disable assertions on a class-by-class basis, using the following syntax: java -ea -da:MyClass TestClass You can enable and disable assertions on a package basis, and any package you specify also includes any subpackages (packages further down the directory hierarchy).
55

Some rules for using Assertion


Do not use assertions to validate arguments to public methods. Do not use assert expressions that cause side effects. Assertions arent guaranteed to always run, so you dont want behavior that changes depending on whether assertions are enabled. Do use assertions - even in public methods - to validate that a particular code block will never be reached. You can use assert false; for code that should never be reached, so that an assertion error is thrown immediately if the assert statement is executed. Do not use assert expressions that can cause side effects. 56

Overriding equals() and hashcode()


The critical methods in class Object are equals(), finalize(), hashCode(), and toString(). equals(), hashCode(), and toString() are public (finalize() is protected). Fun facts about toString():
Override toString() so that System.out.println() or other methods can see something useful. Override toString() to return the essence of your objects state.

Use == to determine if two reference variables refer to the same object. Use equals() to determine if two objects are meaningfully equivalent. If you dont override equals(), your objects wont be useful hashtable/ hashmap keys. If you dont override equals(), two different objects cant be considered the same. Strings and wrappers override equals() and make good hashtable/hashmap keys. When overriding equals(), use the instanceof operator to be sure youre evaluating an appropriate class. When overriding equals(), compare the objects significant attributes.
57

Overriding equals() and hashcode()


If you override equals(), override hashCode(). Classes HashMap, Hashtable, LinkedHashMap, and LinkedHashSet use hashing. A legal hashCode() override compiles and runs. An appropriate hashCode() override sticks to the contract. An efficient hashCode() override distributes keys randomly across a wide range of buckets. To reiterate: if two objects are equal, their hashcodes must be equal. Its legal for a hashCode() method to return the same value for all instances (although in practice its very inefficient).
58

Collections
Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating. Three meanings for "collection":
collection - Represents the data structure in which objects are stored Collection - java.util.CollectionInterface from which Set and List extend Collections - A class that holds static collection utility methods
59

Lists, Sets and Maps


Three basic flavors of collections include Lists, Sets, Maps:
Lists of things: Ordered, duplicates allowed, with an index Sets of things: May or may not be ordered and/or sorted, duplicates not allowed Maps of things with keys: May or may not be ordered and/or sorted, duplicate keys not allowed
60

Subflavors of Collections
Four basic subflavors of collections include Sorted, Unsorted, Ordered, Unordered.
Ordered means iterating through a collection in a specific, nonrandom order. Sorted means iterating through a collection in a natural sorted order.

Natural means alphabetic, numeric, or programmer-defined, whichever applies.

61

More on Collections
Key attributes of common collection classes:
ArrayList: Fast iteration and fast random access Vector: Like a somewhat slower ArrayList, mainly due to its synchronized methods LinkedList: Good for adding elements to the ends, i.e., stacks and queues HashSet: Assures no duplicates, provides no ordering LinkedHashSet: No duplicates; iterates by insertion order or last accessed TreeSet: No duplicates; iterates in natural sorted order HashMap: Fastest updates (key/value pairs); allows one null key, many null values Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed LinkedHashMap: Faster iterations; iterates by insertion order or last accessed, allows one null key, many null values (new with 1.4) 62 TreeMap: A sorted map, in natural order

Object Serialization
Need for Serialization Persistence:
The capability of an object to exist beyond the execution of the program which created it.

In other words :
saving the state of the program in some permanent storage device, such as file

63

Use of Serialization
Lightweight persistence communication via sockets Remote Method Invocation(RMI)

64

Serialization Mechanism
Serializable objects are converted into stream of bytes and are stored in a file (in other words objects are stored in encoded form). Serializable objects implements java.io.Serializable interface.

65

De-Serialization Mechanism
Serialized object is restored into its original form. Information for restoring kept in Serialized form of object itself.

66

Object Serialization
import java.io.*; public class SerializationDemo{ public static void main(String args[]){ try{ //Object Seriliazation MyClass object1 = new MyClass ("hello",-7, 2.7); System.out.println("object1:" + object1); FileOutputStream fos = new FileOutputStream("seril"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); fos.close(); }catch(Exception e) { System.exit(0); } } }
67

Object Deserialization
try{ MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("Object2: " + object2); }catch(Exception e) { System.exit(0); }
68

Object Serialization
class MyClass implements Serializable{ String s; int i; double d; public MyClass (String s, int i, double d){ this.s = s; this.i = i; this.d = d; } public String toString(){ return "s=" + s + ";i=" + i + ";d= " + d ; } }
69

Security issue in serialization


Security: an issue in serialization
Serialized objects can be sent over network Can be accidentally or deliberately modified Also sensitive data can be read

Solution
Encrypt the object during serialization using Security API Ensure that sensitive objects do not implement Serialializable or Externalizable
70

Happy Java Programming!

Вам также может понравиться