Java J2EE Unit 2 Fundamentals and Class Overview

java j2ee unit 2 n.w
1 / 30
Embed
Share

Dive into the fundamentals of Java and J2EE in Unit 2, covering topics like class creation, inheritance, exception handling, and Java applets. Understand how to declare objects, work with methods, constructors, and utilize the 'this' keyword effectively.

  • Java
  • J2EE
  • Fundamentals
  • Class Overview
  • Programming

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


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

  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; Int depth; Long volum; } member of class

  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. Statement Box b1; Effect null b1 b1= new Box(); b1 width height 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. The method have return statement which will return a value of nothing

  6. Engineered for Tomorrow 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()); } 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.

  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 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);} Class box{ Int width; Int depth; Box( int w, int d) { Width=w; Depth=d; } show() { System.out.println(width, depth);}

  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 Control flow for Throw Preceding step Example try { normal program code } catch(Exception e) { exception handling code } try block throw statement unmatched catch matching catch unmatched catch next step

  17. Engineered for Tomorrow Exception hierarchy throwable Exception Error Out of memory error RunTimeException IO Exception AWT Error Thread death ArrayIndexOutofBound Exception Inputmismatch exception Arithmetic classcast nullpointer

  18. Engineered for Tomorrow JAVA APPLET 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.

  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 LIFE CYCLE OF APPLET 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.

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

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

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

  27. Engineered for Tomorrow Steps for converting an application to an applet. 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.

  28. Engineered for Tomorrow Applet program to draw a line 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.

  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 <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes the "Hello, World" applet: <html> <title>The Hello, World Applet</title> <hr> <applet code="HelloWorldApplet.class" width="320" height="120"> If your browser was Java-enabled, a "Hello, World" message would appear here. </applet> <hr> </html>

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

More Related Content