Presentation is loading. Please wait.

Presentation is loading. Please wait.

University of Houston-Clear Lake Proprietary© 1997 No Pointers in Java You cannot cast object or array references into integers or vice-versa You cannot.

Similar presentations


Presentation on theme: "University of Houston-Clear Lake Proprietary© 1997 No Pointers in Java You cannot cast object or array references into integers or vice-versa You cannot."— Presentation transcript:

1 University of Houston-Clear Lake Proprietary© 1997 No Pointers in Java You cannot cast object or array references into integers or vice-versa You cannot do pointer arithmetic Reasons: –Pointers are a notorious source of bugs. Eliminating them simplifies the language and eliminates many potential bugs –Pointers and pointer arithmetic could be used to sidestep Java's run-time checks and security mechanisms

2 University of Houston-Clear Lake Proprietary© 1997 Default Values The value null is a special value that means "no object" or indicates an absence of reference Each primitive type also has a default value, usually zero (or false)

3 University of Houston-Clear Lake Proprietary© 1997 Objects Created Used Destroyed b c

4 University of Houston-Clear Lake Proprietary© 1997 Creating Objects Link to java code for ComplexNumbers Link to java code for ComplexNumbers ComplexNumber my_num; my_num = new ComplexNumber(); my_num.setReal (1.57); my_num.setImaginary(- 7.34); - OR - my_num = new ComplexNumber(1.57,-7.34); Declaring an object Creating the object Setting field values Creating and setting field values

5 University of Houston-Clear Lake Proprietary© 1997 Using Objects Using values of fields double dd; ComplexNumber c = new ComplexNumber( 1.0, 2.0 ); dd = c.getReal() - c.getImaginary (); Setting values of fields c.setReal(dd);

6 University of Houston-Clear Lake Proprietary© 1997 Destroying Objects No old or delete needed Garbage collection is automatic When the number of references to the object reaches zero, the object can not be referenced and is deleted automatically c

7 University of Houston-Clear Lake Proprietary© 1997 Arrays Arrays are manipulated by reference. They are dynamically created with new. They are automatically garbage collected when no longer referred to.

8 University of Houston-Clear Lake Proprietary© 1997 Creating Arrays Two ways to create an array –Use new and give the size of the array: int lookup_table[ ] = new int[8]; –With an initializer, specify the elements: int lookup_table[ ] = {1, 2, 4, 8, 16, 3-2, 64, 128}; May be arbitrary expressions

9 University of Houston-Clear Lake Proprietary© 1997 Multidimensional Arrays byte TwoDimArray[ ][ ] = new byte[256][16]; This statement : –Declares a variable named TwoDimArray of type byte[ ][ ] (array-of-array-of-byte). –Dynamically allocates an array with 256 elements. The type of this newly allocated array is byte[ ][ ], so it can be assigned to the variable we declared. Each element of this new array is of type byte[ ]--a single-dimensional array of byte. – Dynamically allocates 256 arrays of bytes, each of which holds 16 bytes, initialized to their default value of 0.

10 University of Houston-Clear Lake Proprietary© 1997 Triangular Arrays Java implements multidimensional arrays as arrays-of-arrays so multidimensional arrays need not be "rectangular." For example, short triangle[ ][ ] = new short[10][ ]; for (int i = 0; i < triangle.length; i++) { triangle[i] = new short[i+1]; for (int j=0; j < i+1; j++) { triangle[ I ][ j ] = (short) i + j; }

11 University of Houston-Clear Lake Proprietary© 1997 Array Access int a[ ] = new int[100]; a[0] = 0; for (int i = 1; i < a.length; i++) { a[i] = i + a[i-1]; System.out.println(“a[“ + I + ”]=“ + a[I]); }

12 University of Houston-Clear Lake Proprietary© 1997 Arrays as Arguments void reverse(char strbuf[ ], int buffer_size) { char[ ] buffer = new char[500];... } // - or - void reverse(char[ ] strbuf, int buffer_size) { char[ ] buffer = new char[500];... } Note: Strings are not null-terminated arrays of char in Java

13 University of Houston-Clear Lake Proprietary© 1997 Operators Java supports almost all of the standard C operators. These standard operators have the same precedence and associativity in Java as they do in C Java does not support the comma operator for combining two expressions into one No reference or dereference operators (&, *)

14 University of Houston-Clear Lake Proprietary© 1997 New Operators (not in C) + and += operators for string concatenation The instanceof operator has the same precedence as the, and >=. o instanceof C // The instanceof operator returns true if the object o on its left-hand side is an instance of the class C >>> // Right shift with zero extension & and | // Bitwise and and or For booleans, causes both arguments to be evaluated

15 University of Houston-Clear Lake Proprietary© 1997 Control Statements if else do while int j = 10, k = 2; while ( j - - > 0 ) { Object ob = getObject(); if (ob != null) { do {... } while ( k != 0 ); } Boolean

16 University of Houston-Clear Lake Proprietary© 1997 Switch Statement int zz = 2; switch (zz) { case 1: System.out.println(“One \n”); break; case 2: System.out.println(“Two \n”); case 3: System.out.println(“Three\n”); break; default: System.out.println(“Default\n); } What happens?

17 University of Houston-Clear Lake Proprietary© 1997 The for Loop int k; String s; for ( k = 0, s = "testing"; // Initialize variables. (k = 1); // Test for continuation. k++, s = s.substring(1)) { // Increment variables. System.out.println(s); // Loop body. } No commas in test section

18 University of Houston-Clear Lake Proprietary© 1997 The package and import Statements package games.tetris; // must be first statement in the file import java.applet.*; import java.awt.*;

19 University of Houston-Clear Lake Proprietary© 1997 Source Code Structure A file of Java source code has the extension. java. It consists of an optional package statement followed by any number of import statements followed by one or more class or interface definitions. If more than one class or interface is defined in a Java source file, only one of them may be declared public and the source file must have the same name as that public class or interface, plus the. java extension.

20 University of Houston-Clear Lake Proprietary© 1997 Instance vs. Class Methods public class Circle { public double x, y, r; // Class variables // An instance method. Returns the larger circle public Circle bigger (Circle c) { if (c.r > r) return c; else return this; } // A class method. Returns the larger circle public static Circle bigger (Circle a, Circle b) { if (a.r > b.r) return a; else return b; }

21 University of Houston-Clear Lake Proprietary© 1997 Instance vs. Class Methods Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = a.bigger(b); // or, b.bigger(a); And you would invoke the class method like this: Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = Circle.bigger(a,b);

22 University of Houston-Clear Lake Proprietary© 1997 Extending a Class public class GraphicCircle extends Circle { // We've omitted the GraphicCircle constructor, for now. static int num_circles = 0; //static initializer Color outline, fill; public void draw(DrawWindow dw) { dw.drawCircle(x, y, r, outline, fill); } Note: Can use x, y, and r from Circle directly as if defined in GraphicCircle

23 University of Houston-Clear Lake Proprietary© 1997 Final Classes You can declare a class to be final if you don’t want there to be any subclasses Prevents any unwanted extensions of the class Allows compiler to make optimizations java.lang.System is an example

24 University of Houston-Clear Lake Proprietary© 1997 Class Hierarchy a c b Superclasses Subclasses Extensions of a class

25 University of Houston-Clear Lake Proprietary© 1997 Constructor Methods public GraphicCircle(double x, double y, double r, Color outline, Color fill) { this.x = x; this.y = y; this.r = r; this.outline = outline; this.fill = fill; }

26 University of Houston-Clear Lake Proprietary© 1997 Calling the Constructor of the Superclass public GraphicCircle(double x, double y, double r, Color outline, Color fill) { super(x, y, r); // superclass constructor called this.outline = outline; this.fill = fill; }

27 University of Houston-Clear Lake Proprietary© 1997 Rules about Constructors If the first statement in a constructor is not an explicit call to a constructor of the superclass with the super keyword, then Java implicitly inserts the call super() // (Best to add comment) In other words, it calls the superclass constructor with no arguments. If the superclass does not have a constructor that takes no arguments, this causes a compilation error.

28 University of Houston-Clear Lake Proprietary© 1997 No Constructor ? What if a class is declared without any constructor at all? In this case, Java implicitly adds a constructor to the class. This default constructor does nothing but invoke the superclass constructor.

29 University of Houston-Clear Lake Proprietary© 1997 Shadowed Variables If you name a variable in a subclass the same name as one in the superclass, the subclass variable is said to shadow the variable in the superclass The subclass variable is the overriding name Can still refer to the superclass variable as super.whatever Best to avoid this, if possible

30 University of Houston-Clear Lake Proprietary© 1997 Method Overriding When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class is said to override the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, not the old definition of the superclass The practice of overriding is quite common Distinguish between overriding and overloading of methods in same class

31 University of Houston-Clear Lake Proprietary© 1997 Overriding vs. Shadowing class A { int i = 1; int f() { return i; } } class B extends A { int i = 2; // Shadows variable i in class A. int f() { return -i; } // Overrides method f in class A. } public class override_test { public static void main(String args[]) { B b = new B(); System.out.println(b.i); // Refers to B.i; prints 2. System.out.println(b.f()); // Refers to B.f(); prints -2. A a = (A) b; // Cast b to an instance of class A. System.out.println(a.i); // Now refers to A.i; prints 1; System.out.println(a.f()); // Still refers to B.f(); prints -2; }

32 University of Houston-Clear Lake Proprietary© 1997 Invoking an Overridden Method class A { int k = 1; int f() { return k; } // A very simple method } class B extends A { int k; // This variable shadows k in A int f() { // This method overrides f() in A k = super.k + 1; // It retrieves A.k this way return super.f() + k; // And it invokes A.f() this way }

33 University of Houston-Clear Lake Proprietary© 1997 Finalizer Methods Constructor methods are automatically chained, but finalizer methods are not After your finalize() method has done all of its deallocation add the following call: super.finalize(); Note: Will not produce any error if your superclass does not have a finalize method

34 University of Houston-Clear Lake Proprietary© 1997 Encapsulation public class Laundromat { // People can use this class private Laundry[] dirty; // They can't see this public void wash() {... } // They can use these public void dry() {... } // to manipulate the // internal variable }

35 University of Houston-Clear Lake Proprietary© 1997 Visibility of Members Reviewed public - visible to any method private - visible only within the class protected - visible also to subclasses The default package visibility is more restrictive than protected, but less restrictive than private. If a class member is not declared with any of the public, private, or protected keywords, then it is visible only within the class that defines it and within classes that are part of the same package. It is not visible to subclasses unless those subclasses are part of the same package Sometimes called “package visibility”

36 University of Houston-Clear Lake Proprietary© 1997 Packages A package is a group of related and possibly cooperating classes. All non-private members of all classes in the package are visible to all other classes in the package because the classes are assumed to know about, and trust, each other. Caution: Difficulties may arise when you write programs without a package statement. These classes are thrown into a default package with other package-less classes, and all their non-private members are visible throughout the package.

37 University of Houston-Clear Lake Proprietary© 1997 Class Member Accessibility Accessible to: public protected package private Same class yes yes yes yes Class in same package yes yes yes no Subclass in different package yes yes no no Non-subclass, different package yes no no no

38 University of Houston-Clear Lake Proprietary© 1997 Abstract Classes Abstract classes cannot be instantiated The subclasses (if not abstract themselves) can be instantiated, but must implement each method of the superclass a c b

39 University of Houston-Clear Lake Proprietary© 1997 Example of Abstract Class public abstract class Shape { public abstract double area( ); public abstract double circumference( ); } class Circle extends Shape { protected double r; protected static final double PI = 3.14159265358979323846; public Circle( ) { r = 1.0; } public Circle(double r) { this.r = r; } public double area( ) { return PI * r * r; } public double circumference( ) { return 2 * PI * r; } public double getRadius( ) { return r; } } class Rectangle extends Shape { protected double w, h; public Rectangle( ) { w = 0.0; h = 0.0; } public Rectangle(double w, double h) { this.w = w; this.h = h; } public double area( ) { return w * h; } public double circumference() { return 2 * (w + h); } public double getWidth( ) { return w; } public double getHeight( ) { return h; } }

40 University of Houston-Clear Lake Proprietary© 1997 Example - Continued Shape[ ] shapes = new Shape[3]; // Create an array shapes[0] = new Circle(2.0); // Fill in the array... shapes[1] = new Rectangle(1.0, 3.0); shapes[2] = new Rectangle(4.0, 2.0); double total_area = 0; for (int k = 0; k < shapes.length; k++) total_area += shapes[k].area( ); // Compute the areas

41 University of Houston-Clear Lake Proprietary© 1997 Notes about Abstract Classes Subclasses of Shape can be assigned to elements of an array of Shape. No cast is necessary. You can invoke the area() and circumference() methods for Shape objects, even though Shape does not define a body for these methods, because Shape declared them abstract. If Shape did not declare them at all, the code would cause a compilation error.

42 University of Houston-Clear Lake Proprietary© 1997 Interfaces public interface Drawable { public void setColor(Color c); public void setPosition(double x, double y); public void draw(DrawWindow dw); } Interfaces look a lot like abstract classes except all methods are implicitly abstract a c b d

43 University of Houston-Clear Lake Proprietary© 1997 Rules for Interfaces A class must first declare the interface in an implements clause, and then it must provide an implementation (i.e., a body) for all of the abstract methods of the interface.

44 University of Houston-Clear Lake Proprietary© 1997 Interfaces - An Example public class DrawableRectangle extends Rectangle implements Drawable { // New instance variables private Color c; private double x, y; // A constructor public DrawableRectangle(double w, double h) { super(w, h); } // Here are implementations of the Drawable methods. // We also inherit all the public methods of Rectangle. public void setColor(Color c) { this.c = c; } public void setPosition(double x, double y) { this.x = x; this.y = y; } public void draw(DrawWindow dw) { dw.drawRect(x, y, w, h, c); }

45 University of Houston-Clear Lake Proprietary© 1997 Interfaces - Usage Shape[ ] shapes = new Shape[3]; // An array to hold shapes Drawable[ ] drawables = new Drawable[3]; // An array to hold drawables // Create some drawable shapes DrawableCircle dc = new DrawableCircle( 1.1); DrawableSquare ds = new DrawableSquare( 2.5); DrawableRectangle dr = new DrawableRectangle( 2.3, 4.5); // The shapes can be assigned to both arrays shapes[0] = dc; drawables[0] = dc; shapes[1] = ds; drawables[1] = ds; shapes[2] = dr; drawables[2] = dr; // Compute total area and draw the shapes by invoking // the Shape and the Drawable abstract methods double total_area = 0; for ( int k = 0; k < shapes.length; k++) { total_area += shapes[k].area( ); // Compute the area of the shapes drawables[k].setPosition( k*10.0, k*10.0); drawables[k].draw(draw_window); // draw_window defined elsewhere }

46 University of Houston-Clear Lake Proprietary© 1997 Extended Interfaces An interface that extends more than one interface inherits all the abstract methods and constants fromeach of those interfaces It may define its own additional abstract methods and constants A class that implements such an interface must implement the abstract methods defined in the interface itself as well as all the abstract methods inherited from all the super-interfaces

47 University of Houston-Clear Lake Proprietary© 1997 Summary of Chapter 3 A class is a collection of data and methods that operate on that data. An object is a particular instance of a class. Object members (fields and methods) are accessed with a dot between the object name and the member name. Instance (non-static) variables occur in each instance of a class. Class (static) variables are associated with the class. There is one copy of a class variable regardless of the number of instances of a class. Instance (non-static) methods of a class are passed an implicit this argument that identifies the object being operated on. Class (static) methods are not passed a this argument and therefore do not have a current instance of the class that can be used to implicitly refer to instance variables or invoke instance methods.

48 University of Houston-Clear Lake Proprietary© 1997 Summary - Continued Objects are created with the new keyword, which invokes a class constructor method with a list of arguments. Objects are not explicitly freed or destroyed in any way. The Java garbage collector automatically reclaims objects no longer used. If the first line of a constructor method does not invoke another constructor with a this() call, or a superclass constructor with a super( ) call, Java automatically inserts a call to the superclass constructor that takes no arguments. This enforces "constructor chaining." If a class does not define a constructor, Java provides a default constructor. A class may inherit the non-private methods and variables of another class by "subclassing"--i.e., by declaring that class in its extends clause

49 University of Houston-Clear Lake Proprietary© 1997 Summary - Continued java.lang.Object is the default superclass for a class. It is the root of the Java class hierarchy and has no superclass itself. All Java classes inherit the methods defined by Object. Method overloading is the practice of defining multiple methods which have the same name but have different argument lists. Method overriding occurs when a class redefines a method inherited from its superclass. Dynamic method lookup ensures that the correct method is invoked for an object, even when the object is an instance of a class that has overridden the method. static, private, and final methods cannot be overridden and are not subject to dynamic method lookup. This allows compiler optimizations such as inlining. From a subclass, you can explicitly invoke an overridden method of a superclass with the super keyword. You can explicitly refer to a shadowed variable with the super keyword.

50 University of Houston-Clear Lake Proprietary© 1997 Summary - Concluded Data and methods may be hidden or encapsulated within a class by specifying the private or protected visibility modifiers. Members declared public are visible everywhere. Members with no visibility modifiers are visible only within the package. An abstract method has no method body (i.e., no implementation). An abstract class contains abstract methods. The methods must be implemented in a subclass before the subclass can be instantiated. An interface is a collection of abstract methods and constants (static final variables). Declaring an interface creates a new data type. A class implements an interface by declaring the interface in its implements clause and by providing a method body for each of the abstract methods in the interface.

51 University of Houston-Clear Lake Proprietary© 1997 Java 1.1 - What’s New? Inner classes Java Beans A framework for defining reusable modular software components. Internationalization A variety of new features that make it possible to write programs that run around the globe. New event model A new model for handling events in graphical user interfaces that should make it easier to create those interfaces. Other new AWT features The Java 1.1 AWT includes support for printing, cut-and-paste, popup menus, menu shortcuts, and focus traversal. It has improved support for colors, fonts, cursors, scrolling, image manipulation, and clipping. Applets JAR files allow all of an applet's files to be grouped into a single archive. Digital signatures allow trusted applets to run with fewer security restrictions. The HTML tag has new features.

52 University of Houston-Clear Lake Proprietary© 1997 Java 1.1 - More of What’s New? Object serialization Objects can now be easily "serialized" and sent over the network or written to disk for persistent storage. Security Java 1.1 includes a new package that supports digital signatures, message digests, key management, and access control lists. Java Database Connectivity (JDBC) A new package that allows Java programs to send SQL queries to database servers. It includes a "bridge" that allows it to inter-operate with existing ODBC database servers. Remote Method Invocation (RMI) An interface that supports distributed Java applications in which a program running on one computer can invoke methods of Java objects that exist on a different computer.

53 University of Houston-Clear Lake Proprietary© 1997 23 Packages in the Core Java API java.applet java.awt, java.awt.datatransfer, java.awt.event, java.awt.image, java.awt.peer java.beans, java.reflect java.io, java.lang, java.math, java.net java.rmi, java.rmi.dgc, java.rmi.registry, java.rmi.server java.security, java.security.acl, java.security.interfaces java.sql, java.text, java.util, java.util.zip

54 University of Houston-Clear Lake Proprietary© 1997 “Deprecated” Features Compile using the -deprecation flag, and javac provides a detailed warning about each use of a deprecated feature For example, the old AWT event-handling model has been deprecated in Java 1.1


Download ppt "University of Houston-Clear Lake Proprietary© 1997 No Pointers in Java You cannot cast object or array references into integers or vice-versa You cannot."

Similar presentations


Ads by Google