Está en la página 1de 52

Wrapper Classes

Wrapper Class
Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.

Primitives & Wrappers


Java has a wrapper class for each of the eight primitive data types:

Primitive Type boolean byte char double

Wrapper Class Boolean Byte Character Double

Primitive Type float int long short

Wrapper Class Float Integer Long Short

Use of the Wrapper Classes


Javas primitive data types (boolean, int, etc.) are not classes. Wrapper classes are used in situations where objects are required, such as for elements of a Collection:
List<Integer> a = new ArrayList<Integer>(); methodRequiringListOfIntegers(a);

Value => Object: Wrapper Object Creation


Wrapper.valueOf() takes a value (or string) and returns an object of that class: Integer i1 = Integer.valueOf(42); Integer i2 = Integer.valueOf(42); Boolean b1 = Boolean .valueOf(true); Boolean b2 = Boolean .valueOf(true);

Long n1 = Long.valueOf(42000000L); Long n1 = Long.valueOf(42000000L);

Object => Value


Each wrapper class Type has a method typeValue to obtain the objects value:
Integer i1 = Integer.valueOf(42); Boolean b1 = Boolean.valueOf(false); System.out.println(i1.intValue()); System.out.println(b1.intValue()); => 42 false

String => value


The Wrapper class for each primitive type has a method parseType() to parse a string representation & return the literal value.
Integer.parseInt(42) Boolean.parseBoolean(true) Double.parseDouble(2.71) // => 42 => true => 2.71

Common use: Parsing the arguments to a program:

Parsing argument lists


// Parse int and float program args. public parseArgs(String[] args) { for (int i = 0; i < args.length; i++) { try { println(Integer.parseInt(args[i])); } catch (Exception e) { try { println(Float.parseFloat(args[i])); } finally { } }}}

Package
Package A collection of related classes and/or interfaces Examples: The Java API
java.lang Essential classes for the Java language java.text Facilities for formatting text output java.util Special utilities (e.g. Scanner) java.net Network communication

Packages can be divided into subPackages


java.awt Classes for GUIs and graphics java.awt.font Classes and interface for fonts java.awt.geom Classes for 2-dimensional objects

Access to Package Members


Use fully qualified name: java.util.Scanner sc = new java.util.Scanner(System.in); Use import to tell Java where to look for things defined outside your program import java.util.Scanner; Scanner sc = new Scanner (System.in); Using * imports all classes in package: import java.util.*; Scanner sc = new Scanner (System.in); Multiple import statements are allowed java.lang package gets automatically imported by every Java program

User-Defined Packages

Packages enable a programmer organize the code into smaller logically related units. A large program may consists of hundreds of classes Every class is part of some package If you do not specify a package a class becomes part of the default package Access Classes defined within the same package can access one another more easily (no need for imports, fully qualified names)

Defining Packages
To define: add package statement to specify package containing the classes of a file package mypackage; public class myClass { } // myClass is part of mypackage Must be first non-comment statement in file Packages organized into subpackages using the notation package mypackage.mysubpackage; public class myClass2 { } // myClass2 is part of // mysubpackage, which is within mypackage

Class Access and Packages


Classes within a package can refer to each other without full qualification If a class, or member within a class, is not declared public, it can only be accessed by other classes within the package A public class can be accessed from other packages Its name is fully qualified or it must be is imported to achieve this Importing a package does not automatically import subpackages E.g. import java.awt.* does not import java.awt.font

Abstract Classes

Abstract Classes
A superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Methods declared in the superclass are sometimes referred to as subclasss responsibility because they have no implementation specified in the superclass. To declare an abstract method, the general form is: abstract type name(parameter-list);

Abstract Classes (Contd..)


Any class that contains one or more abstract methods must also be declared abstract. There can be no objects of an abstract class. You cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. It is possible to create a reference to an abstract class so that it can be used to point to a subclass.

// Abstract classes abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1=a; dim2=b; } abstract double area(); }

class Rectangle extends Figure { Rectangle(double a, double b) { super(a,b); } double area() { System.out.println("Inside area for Rectangle"); return dim1*dim2; } }

class Triangle extends Figure { Triangle(double a, double b) { super(a,b); } double area() { System.out.println("Inside area for Triangle"); return dim1*dim2 / 2; } }

class AbstractArea { public static void main(String s[]) { Figure f=new Figure(10,10); // illegal now Rectangle r=new Rectangle(9,5); Triangle t=new Triangle(10,8); Figure fig; fig=r; System.out.println("Area is " + fig.area()); fig=t; System.out.println("Area is " + fig.area()); fig=f; System.out.println("Area is " + fig.area()); } }

Interfaces

Java Interface
A Java interface is a collection of constants and abstract methods abstract method: a method header without a method body; we declare an abstract method using the modifier abstract Methods in an interface have public visibility by default Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.

23

Defining an Interface
An interface is defined much like a class. The general form of an interface is: access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1=value; ------------------}

Interface: Syntax
interface is a reserved word

public interface Doable { public static final String NAME;

public public public public


}

void doThis(); int doThat(); void doThis2 (float value, char ch); boolean doTheOther (int num);

A semicolon immediately follows each method header No method in an interface has a definition (body)
25

Interfaces Contd..
Once it is defined, any number of classes can implement an interface. One class can implement any number of interfaces. To implement an interface, a class must create the complete set of methods defined by the interface. Each class is free to determine the details of its own implementation. Interfaces are designed to support dynamic method resolution at run time. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface.

Contd..
Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they cannot be changed by the implementing class. They must be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public. Example: interface Callback { void callback( int param); }

Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: access class classname [extends superclass] [implements interface[,interface]] { // class- body }

Implementing Interfaces
public class Something implements Doable { implements is a public void doThis () { reserved word // whatever } public void doThat () { // whatever } // etc. } public class ManyThings implements Doable, AnotherDoable
29

Each method listed in Doable is given a definition

Contd..
Also the type signature of the implementing method must match exactly the type signature specified in the interface definition. Example: class Client implements Callback{ //implement Callbacks interface public void callback( int p) { System.out.println( callback called with + p); } }

Contd..
Example: class Client implements Callback { public void callback( int p) { System.out.println( callback called with + p); } void nonIfaceMeth( ) { System.out.println( Classes that implement interfaces + may also define other members, too.); } }

Accessing Implementations Through Interface References


Variables can be declared as object references using an interface type. Any instance of any class that implements the declared interface can be referred to by such a variable. When a method called through one of these references, the correct version will be called based on the actual instance of the interface being referred to.

Contd..
The method to be executed is looked up dynamically at run time, allowing classes to be created later than the code which calls methods on them. The calling code can dispatch through an interface without having to know anything about the callee. An interface reference variable only has knowledge of the methods declared by its interface declaration.

Contd..
An example showing how an interface reference variable can access an implementation object. class TestInterface { public static void main (String p[]) { Callback c = new Client( ); c.callback( 42 ); } }

Polymorphism via Interfaces..


Example to demonstrate the polymorphic power of such a reference: class AnotherClient implements Callback { public void callback ( int p) { System.out.println( Another version of call back); System.out.println( p squared is + (p*p)); } }

Polymorphism via Interfaces..


class TestIface2 { public static void main ( String p[]) { Callback c = new Client ( ); AnotherClient ob = new AnotherClient ( ); c.callback( 42 ); c = ob; c.callback ( 42 ); } }

Contd..
If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract. One interface can inherit another by use of the keyword extends. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.

Vectors

Vectors
Java Vector is a resizable array of Objects which implements the List interface .Like an array, elements of the Java Vector can be accessed using an index. Java Vector is similar to Java ArrayList, but it is synchronized. An array is a data type for collecting a fixed number of data of the same type. Vectors are dynamically-allocated. They aren't declared to contain a type of variable; instead, each Vector contains a dynamic list of references to other objects. The Vector class is found in the java.util package

Vector Constructors
Vector( ) Vector(int size ) Vector(int size, int incr) Vector(Collection c) The first form creates a default vector, which has an initial size of 10. The second form creates a vector whose initial capacity is specified by size. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time a vector is resized upward. The fourth form creates a vector that contains the elements of collection c.

Vectors Contd..
Vector defines these protected data members: int capacityIncrement; The increment value is stored in capacityIncrement

int elementCount; The number of elements currently in the vector is stored in elementCount.
Object elementData[]; The array buffer into which the components of the vector are stored.

Contd..
boolean isEmpty( ) Object lastElement( ) int lastIndexOf(Object element) void removeAllElements( ) boolean removeElement(Object element) void removeElementAt(int index) void setElementAt(Object element, int index) void setSize(int size) int size( ) String toString( ) void trimToSize( )

Creating Vectors
Whenever you start working with vectors in Java, it is convenient to first import the Vector class from the java.util package. import java.util.Vector; // load Vector package To create a vector, we use three steps: Declare a variable to hold the vector. Vector v; // declare a vector object Declare a new vector object and assign it to the vector variable. v = new Vector(); // create an empty vector object You may also add a number to specify the (initial) capacity of the object, e.g., v = new Vector(5); Store things in the vector, e.g., with the add( ) method.

1) 2)

3)

Contd..
v.add(new Integer(1)); // add first vector element v.add(new Float(1.9999)); // add another vector element for (int i=2; i<10; i++) { int lastInt = ((Number) v.lastElement()).intValue(); v.add(new Integer(i + lastInt)); // recursively add more elements }

Accessing, Changing, and Removing Elements


The size method returns the current number of elements in the vector. v.size(); The size can grow and shrink as needed.

It may differ from the capacity of the vector.


To get a specific element from a vector, use the get(int) method. To remove a specific element from a vector, use the remove(int) method.

Contd..
An ArrayIndexOutOfBoundsException is thrown when an invalid index is given. You can use this method together with size method to step in a for-loop through all elements. e.g. for (int i=0; i<v.size(); i++) { System.out.println("v[" + i + "] = " + v.get(i)); }

Contd..
An alternative way of stepping through vectors is provided by the Enumeration interface. public interface Enumeration { boolean hasMoreElements(); Object nextElement(); }

Contd..
to iterate through the set of values using while-loop Enumeration e = vector.elements(); // get all vector elements while (e.hasMoreElements()) // step through all vector elements { Object obj = e.nextElement(); // work with the object ..... }

Example
import java.util.*; public class VectorDemo { public static void main(String[] args) {
Vector<Object> vector = new Vector<Object>(); int primitiveType = 10; Integer wrapperType = new Integer(20); String str = "tapan joshi"; vector.add(primitiveType); vector.add(wrapperType); vector.add(str); vector.add(2, new Integer(30)); System.out.println("the elements of vector: " + vector); System.out.println("The size of vector are: " + vector.size()); System.out.println("The elements at position 2 is: " + vector.elementAt(2)); System.out.println("The first element of vector is: " + vector.firstElement()); System.out.println("The last element of vector is: " + vector.lastElement()); vector.removeElementAt(2);

System.out.println("the elements of vector----: " + vector); Enumeration e=vector.elements(); System.out.println("The elements of vector: " + vector); while(e.hasMoreElements()){ System.out.println("The elements are: " + e.nextElement()); } } /* } the elements of vector: [10, 20, 30, tapan joshi] The size of vector are: 4 The elements at position 2 is: 30 The first element of vector is: 10 The last element of vector is: tapan joshi The elements of vector: [10, 20, tapan joshi] The elements are: 10 The elements are: 20 The elements are: tapan joshi */

Contd..
To set an element at a specific index in a vector, use the setElementAt method.
public final synchronized void setElementAt( java.lang.Object obj, int index);

Returns the element at the specified index. The element is not removed from the vector.
public final synchronized java.lang.Object elementAt( int index);

The table below shows the difference in style.


array x = a[i]; a[i] = x; vector x = v.elementAt(i); v.setElementAt(x, i);

example
import java.util.*; public class Program { public static void main(String[] args) { // Create a Vector and add some elements to it. Vector v = new Vector(); v.add("1"); v.add("2"); v.add("3"); // Change the element at index 1. v.setElementAt("4", 1); // Display the contents of the Vector. Enumeration vEnum = v.elements(); while (vEnum.hasMoreElements()) { System.out.println(vEnum.nextElement()); } } }

También podría gustarte