3. Method Declarations
General format of method declaration:
Modifier return-type method-name( parameter1, …, parameterN )
{
body (declarations and statements);
}
Modifiers—such as public, private, and others you will learn later.
return type—the data type of the value returned by the method, or void if
the method does not return a value.
Method body can also return values:
return expression;
4. Access members of a class
Class A
{
int i;
char ch;
void set()
{ i=20; }
int get()
{return i; }
}
stack Heap
i
ch
A
How to access member of class A ?
A a= new A();
a.i;
a.ch;
a.set();
5. Types of Methods (4 basic types )
– Modifier (sometimes called a mutator)
Changes the value associated with an attribute of the object
E.g. A method like set()
– Accessor
Returns the value associated with an attribute of the object
E.g. A method like Get()
– Constructor
Called once when the object is created (before any other
method will be invoked)
E.g. A(int i)
– Destructor
Called when the object is destroyed
E.g.~A( )
6. Constructor
Same name as class name
No return type (as methods)
Why we need constructors?
Initialize an object
Default cons (if we not defined)
– No parameter
– Ex: A()
{
}
7. Parameterized constructor
A(int in) A(int in, char c)
{ {
i=in; i=in;
} ch=c;
}
Created when object init
Can define any number of constructors
8. Example 2: two classes
class aa2
{
int i;
char ch;
void set()
{ i=20;}
int get()
{return i;}
}
8
public class aa4
{
public static void main(String args[])
{
aa2 obj= new aa2();
int b;
obj.set();
b= obj.get();
System.out.println("i="+ obj.i);
System.out.println("i="+ b);
}
}
9. Example 3: two classes uses cons.
class aa2
{
int i;
char ch;
void set()
{ i=20;}
int get()
{return i;}
aa2 (int in, char c)
{
i=in; ch=c;
}
}9
public class aa4
{
public static void main(String args[])
{
aa2 obj= new aa2(20,‘g’);
System.out.println("i="+ obj.i);
System.out.println("i="+ obj.ch);
}
}
10. Example 4: single class
public class aa1
{
int i;
char ch;
void set()
{ i=20;}
int get()
{return i;}
10
public static void main(String args[])
{
aa1 a= new aa1();
int b;
a.set();
b=a.get();
System.out.println("i="+ a.i);
System.out.println("i="+ b);
}
}
11. Introduction to Applets
Java applet is a small appln. written in Java
delivered to users in the form of bytecode
user can launches Java applet from a web page
it can appear in a frame of the web page, in a
new application window, or in Sun's
AppletViewer, a stand-alone tool for testing
applets
11
12. Applet Example 1
/*
<APPLET CODE="app1.class" WIDTH=150 HEIGHT=100>
</APPLET>
*/
import java.applet.Applet;
import java.awt.Graphics;
public class app1 extends Applet {
public void paint (Graphics g) {
g.drawString("Hello!",50,20);
} }
12
14. Execution through HTML file
<HTML>
<HEAD>
<TITLE> A simple Program</TITLE>
</HEAD>
<BODY> Here is the output:
<APPLET CODE="app1.class" WIDTH=150 HEIGHT=100>
</APPLET>
<BODY>
</HTML>
Store with name app1.htm
Execute from browser: C:javaapp1.htm14