Presentation is loading. Please wait.

Presentation is loading. Please wait.

JAVA & J2EE Unit 2 Engineered for Tomorrow Prepared by Santhiya.M & Ganga V C Department OF Computer Science and Engineeering.

Similar presentations


Presentation on theme: "JAVA & J2EE Unit 2 Engineered for Tomorrow Prepared by Santhiya.M & Ganga V C Department OF Computer Science and Engineeering."— Presentation transcript:

1 JAVA & J2EE Unit 2 Engineered for Tomorrow Prepared by Santhiya.M & Ganga V C Department OF Computer Science and Engineeering

2 Engineered for Tomorrow OVERVIEW CLASS FUNDAMENTALS INHERITANCE EXCEPTION HANDLING JAVA APPLETS

3 Engineered for Tomorrow CLASS FUNDAMENTALS CLASS: Class creates a new data type Class is used to create object Class is template of the object Object is an instance for the class General form: Class classname{ Type inst-var1; Type inst-var2; //.. Type inst-varn; Type methodname1(parameter-list){ //body of method } Type methodname2(parameter-list){ //body of method } //.. Type methodnamen(parameter-list){ //body of method } Method and instance variable are member of the class Sample class Class box { Int width; Int height; member of Int depth; class Long volum; }

4 Engineered for Tomorrow Declaring the objects 1.Declare a variable for the class type 2.Using new operator dynamically allocate memory for the object created. StatementEffect Box b1;null b1 b1= new Box();width b1height depth Box object

5 Engineered for Tomorrow METHODS Methods are functions in Java. It is declared and defined inside the class. Methods declared inside the class operates on the instance variable of the class The general form of the method: Type name(parameter-list){ // body of method } Type is the type of the value the return statement returns. Parameter list is the formal parameter. return statement The method have return statement which will return a value of nothing

6 Engineered for Tomorrow CONSTRUCTORS Constructor is the method which has same name as class name. Constructor initializes an object immediately upon creation It is automatically called when an object is created. It has no return value type, not even void. The implicit return type of a class constructor is class type itself. Constructor can be overloaded and parameterized. Class Box { Int width, height, depth; Box(int w, int h, int d) { Width=w; Height= h; Depth= d;} Int volume() { Return width*height*depth; } Class boxdemo { Public static void main(String args[]) { Box b1=new box(10, 20, 30); System.out.println(b1.volume()); } Class Box { Int width, height, depth; Box(int w, int h, int d) { Width=w; Height= h; Depth= d;} Int volume() { Return width*height*depth; } Class boxdemo { Public static void main(String args[]) { Box b1=new box(10, 20, 30); System.out.println(b1.volume()); }

7 Engineered for Tomorrow The this keyword Instance variables are hidden by the parameters and local variables in a method. this keyword are used inside the methods. this keyword are used to refer the object on which the method is invoked. This keyword refers current instance of the object. Box( int width, int depth, int height) { this.width=width; this.height-height; this.depth=depth; }

8 Engineered for Tomorrow The this keyword…. This keyword are used to refer overloaded constructor class Loan{ private double interest; private String type; public Loan(){ this(“personal loan”); } public Loan(String type){ this.type = type; this.interest = 0.0; }

9 Engineered for Tomorrow The this keyword…. Cannot assign value to this variables. It will result in compilation error this = new Loan(); // lead to error this can be used to return object public Loan getLoan(){ return this; // return object } this is a valid return value

10 Engineered for Tomorrow Garbage collection Java run time automatically, randomly recover the memory from the objects to which no reference exist When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. There is no explicit deletion and no memory is given back to the operating system. Every object tree must have one or more root objects. As long as the application can reach those roots, the whole tree is reachable Unreachable objects roots

11 Engineered for Tomorrow finalize Method The action that is to be performed by after destroying the object. Finalize method is called prior to garbage collection It is not automatically called by compiler like constructor Finalize method is called only once by garbage collection thread. Any exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I doubt if you find any trace of it. Proteced void finalize() { // finalize code }

12 Engineered for Tomorrow Inheritance Important OOPs concept Creation of hierarchal classification Class that is inherited is called super class Class that does inheritance is called sub class extend keyword is used for inheritance. Class superclass{ Int I,j; Void show() { //----- }} Class subclass extend superclass{ Int k; Void display() {\\--- }} Variable I and j can be used by subclass Method show can be used by subclass Private member in super class cannot be used by sub class

13 Engineered for Tomorrow Using Super Two general form 1.Calling super class constructor 2.Accessing super class member that has been hidden by a member of sub class Calling super class constructor Super(parameter_list); Class box{ Int width; Int depth; Box( int w, int d) { Width=w; Depth=d; } show() { System.out.println(width, depth);} Class boxe extend box {int height; Boxe(int w, int d, int h) { Super(w,d);//super class constructor Height=h; } Show() { Super.show();// super class show method System.out.println(height);}

14 Engineered for Tomorrow Exception handling An Error is any unexpected result obtained from a program during execution. Unhandled errors may led to abnormal program termination. Errors should be handled by the programmer, to prevent them from reaching the user. Some typical causes of errors: Memory errors File system errors Calculation errors (i.e. divide by 0) Array errors (i.e. accessing element –1) Conversion errors

15 Engineered for Tomorrow Exception handling… Code to be monitored for exception is kept in try block Action to be taken for exception is kept in catch block After catch the things to be executed are kept in finally block Throw and throws are used to manually throw an error. Catch block catches all exceptions of its type and subclasses of its type If there are multiple catch blocks that match a particular exception type, only the first matching catch block executes Makes sense to use a catch block of a superclass when all catch blocks for that class’s subclasses will perform same functionality

16 Engineered for Tomorrow Preceding step try block throw statement unmatched catch matching catch unmatched catch next step Control flow for Throw Example – try { … normal program code } catch(Exception e) { … exception handling code }

17 Engineered for Tomorrow throwable ExceptionError RunTimeExceptionIO ExceptionAWT Error Out of memory error Thread death ArrayIndexOutofBound Exception Inputmismatch exception classcastnullpointer Arithmetic Exception hierarchy

18 Engineered for Tomorrow An applet is a Java program that runs in a Web browser. An applet is a Java class that extends the java.applet.Applet class. No main() in java applet program. Applets are designed to be embedded within an HTML page. Code of the applet is downloaded when user view the applet. A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime environment. Like applet viewer The JVM on the user's machine creates an instance of the applet class and invokes various methods during the applet's lifetime. Applets have strict security rules that are enforced by the Web browser. Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file. JAVA APPLET

19 Engineered for Tomorrow Applets in the Class Hierarchy

20 Engineered for Tomorrow Designing an Applet An applet class can be designed as a derived class of JApplet in much the same way that regular Swing GUIs are defined as derived classes of JFrame However, an applet normally defines no constructors – The method init performs the initializations that would be performed in a constructor for a regular Swing GUI

21 Engineered for Tomorrow Designing an Applet Components can be added to an applet in the same way that a component is added to a JFrame – The method add is used to add components to an applet in the same way that components are added to a JFrame

22 Engineered for Tomorrow How Applets Differ from Swing GUIs Some of the items included in a Swing GUI are not included in an applet Applets do not contain a main or setVisible method – Applets are displayed automatically by a Web page or an applet viewer Applets do not have titles – Therefore, they do not use the setTitle method – They are normally embedded in an HTML document, and the HTML document can add any desired title

23 Engineered for Tomorrow Four methods in the Applet: init: This method is intended for whatever initialization is needed for the applet. start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. stop: This method is automatically called when the user moves off the page on which the applet sits. destroy: This method is only called when the browser shuts down normally. paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. LIFE CYCLE OF APPLET

24 Engineered for Tomorrow LIFE CYCLE OF APPLET Init() Start() Paint() Stop() Destroy()

25 25 import java.awt.*; import java.applet.*; public class WelcomeApplet extends Applet { public void init() { } public void paint(Graphics g) { g.drawString("Welcome to Java Programming!", 25, 25 ); } import java.awt.*; import java.applet.*; public class WelcomeApplet extends Applet { public void init() { } public void paint(Graphics g) { g.drawString("Welcome to Java Programming!", 25, 25 ); } extends allows us to inherit the capabilities of class Applet. Method paint is guaranteed to be called in all applets. Its first line must be defined as above. Engineered for Tomorrow Simple applet program

26 Engineered for Tomorrow 1 // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java. 3 4 // Java packages 5 import java.awt.Graphics; // import class Graphics 6 import javax.swing.JApplet; // import class JApplet 7 8 public class WelcomeApplet extends JApplet { 9 10 // draw text on applet ’ s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); 15 16 // draw a String at x-coordinate 25 and y-coordinate 25 17 g.drawString( "Welcome to Java Programming!", 25, 25 ); 18 19 } // end method paint 20 21 } // end class WelcomeApplet 1 // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java. 3 4 // Java packages 5 import java.awt.Graphics; // import class Graphics 6 import javax.swing.JApplet; // import class JApplet 7 8 public class WelcomeApplet extends JApplet { 9 10 // draw text on applet ’ s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); 15 16 // draw a String at x-coordinate 25 and y-coordinate 25 17 g.drawString( "Welcome to Java Programming!", 25, 25 ); 18 19 } // end method paint 20 21 } // end class WelcomeApplet import allows us to use predefined classes (allowing us to use applets and graphics, in this case). extends allows us to inherit the capabilities of class JApplet. Method paint is guaranteed to be called in all applets. Its first line must be defined as above.

27 Engineered for Tomorrow Make an HTML page with the appropriate tag to load the applet code. Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be loaded. Eliminate the main method in the application. Do not construct a frame window for the application. Application will be displayed inside the browser. Move any initialization code from the frame window constructor to the init method of the applet. Don't need to explicitly construct the applet object.the browser instantiates it and calls the init method. Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file. Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits. If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars. The applet is displayed automatically. Steps for converting an application to an applet.

28 Engineered for Tomorrow import java.awt.*; import java.applet.*; public class WelcomeApplet2 extends Applet { public void init() { } public void paint(Graphics g) { g.drawString( "Welcome to", 25, 25 ); g.drawString( "Java Programming!", 25, 40 );} } import java.awt.*; import java.applet.*; public class WelcomeApplet2 extends Applet { public void init() { } public void paint(Graphics g) { g.drawString( "Welcome to", 25, 25 ); g.drawString( "Java Programming!", 25, 40 );} } The two drawString statements simulate a newline. In fact, the concept of lines of text does not exist when drawing strings. Applet program to draw a line

29 Engineered for Tomorrow Invoking an applet An applet may be invoked by using an HTML file and viewing the file through an applet viewer or Java-enabled browser. The tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet: The Hello, World Applet If your browser was Java-enabled, a "Hello, World" message would appear here.

30 Engineered for Tomorrow getApplet(String) getApplet Gets an applet by name. getApplets() getApplets Enumerate the applets in this context. getAudioClip(URL) getAudioClip Gets an audio clip. getImage(URL) getImage Gets an image. showDocument(URL) showDocument Show a new document. showStatus(String) showStatus Show a status string. AppletContext interface methods


Download ppt "JAVA & J2EE Unit 2 Engineered for Tomorrow Prepared by Santhiya.M & Ganga V C Department OF Computer Science and Engineeering."

Similar presentations


Ads by Google