Unit I Java & J2EE
Unit I Java & J2EE
2 Marty Hall, Larry Brown, Core Servlets and Java Server Pages. Volume 1: Core
Technologies. Second Edition
• Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:
return value;
Adding a Method to the Box Class
Returning a Value
Important Things To Understand
About Returning Values
• The type of data returned by a method must be compatible with the return
type specified by the method.
• For example, if the return type of some method is boolean, you could not return an
integer.
• The variable receiving the value returned by a method (such as vol, in this
case) must also be compatible with the return type specified for the
method.
• The call to volume( )could have been used in the println( )statement
directly
System.out.println("Volume is " + mybox1.volume());
Adding a Method That Takes
Parameters
Constructors
• Initializes an object immediately upon creation.
• It has the same name as the class in which it resides
• Syntactically similar to a method.
• It is automatically called immediately after the object is created,
before the new operator completes.
• Constructors look a little strange because they have no return type,
not even void.
• Initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.
Example
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Calling the
Constructor/Instantiating an
object
• General Syntax
class-var = new classname( );
• Example
Box mybox1 = new Box();
Parameterized Constructors
• Default constructor initializes all object with the same data.
• Dynamic initialization is required to allow different object with its own
data.
• Parameterized Constructor can be used to initialize each object with
different data.
Example
/* Here, Box uses a parameterized constructor to
initialize the dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The this Keyword
• A method will need to refer to the object that invoked it.
• Java defines the this keyword.
• this can be used inside any method to refer to the current object.
• this is always a reference to the object on which the method was invoked
• Example
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Instance Variable Hiding
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Overloading Methods
• Two or more methods within the same class that share the same name, as
long as their parameter declarations are different.
• The methods are said to be overloaded, and the process is referred to as
method overloading.
• When an overloaded method is invoked, Java uses the type and/or number
of arguments as its guide to determine which version of the overloaded
method to actually call.
• Overloaded methods must differ in the type and/or number of their
parameters.
• While overloaded methods may have different return types, the return type
alone is insufficient to distinguish two versions of a method.
Overloading Constructors
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Using Objects as Parameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
Main Class
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
A Closer Look at Argument
Passing
• Call by Value
• Primitive data like int, float, double, etc
• Call by Reference
• Objects like String, Integer, Float, user defined classes objects (Students,
Employees, Projects etc)
Returning Objects
// Returning an object. public static void main(String args[]) {
class Test { Test ob1 = new Test(2);
int a; Test ob2;
Test(int i) { ob2 = ob1.incrByTen();
a = i; System.out.println("ob1.a: " + ob1.a);
} System.out.println("ob2.a: " + ob2.a);
Test incrByTen() { ob2 = ob2.incrByTen();
Test temp = new Test(a+10); System.out.println("ob2.a after second
increase: “ + ob2.a);
return temp;
} }
}
}
class RetOb {
Recursion
// A simple example of recursion.
class Factorial {
// this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Introducing Access Control
• Control what parts of a program can access the members of a class.
• Prevent misuse
• Java’s access specifiers are public, private, and protected.
• protected applies only when inheritance is involved.
• A member of a class is modified by the public specifier, then that
member can be accessed by any other code.
• When a member of a class is specified as private, then that member
can only be accessed by other members of its class.
• Default access is public
/* This program demonstrates the difference public static void main(String args[]) {
between public and private. Test ob = new Test();
*/ // These are OK, a and b may be accessed
directly
class Test {
ob.a = 10;
int a; // default access
ob.b = 20;
public int b; // public access
// This is not OK and will cause an error
private int c; // private access
// ob.c = 100; // Error!
// methods to access c
// You must access c through its methods
void setc(int i) { // set c's value
ob.setc(100); // OK
c = i;
System.out.println("a, b, and c: " + ob.a +
}
""+
int getc() { // get c's value
ob.b + " " + ob.getc());
return c;
}
}
}
}
class AccessTest {
Understanding static
• Static defines a class member that will be used independently of any object of that
class.
• To create such a member, precede its declaration with the keyword static.
• When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
• Both methods and variables can be declared static.
• The most common example of a static member is main( ).
• main( ) is declared as static because it must be called before any objects exist.
• Instance variables declared as static are global variables.
• When objects of its class are declared, no copy of a static variable is made.
• All instances of the class share the same static variable
Methods declared as static have
several restrictions
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Introducing final
• A variable can be declared as final.
• Prevents its contents from being modified.
• This means that you must initialize a final variable when it is declared.
• Example
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Inheritance
• Allows the creation of hierarchical classifications.
• Create a general class that defines traits common to a set of related
items.
• This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
• A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• A subclass is a specialized version of a superclass.
• It inherits all of the instance variables and methods defined by the
superclass and adds its own, unique elements.
Inheritance Basics
• To inherit a class incorporate the definition of one class into another
by using the extends keyword.
// A simple example of inheritance.
// Create a superclass.
class A {
private int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
The general form of a class
declaration that inherits a
superclass
class subclass-name extends superclass-name {
// body of class
}
Member Access and Inheritance
• A subclass includes all of the members of its superclass, it cannot
access those members of the superclass that have been declared as
private
/* In a class hierarchy, private members remain class Access {
private to their class. public static void main(String args[]) {
This program contains an error and will not B subOb = new B();
compile. subOb.setij(10, 12);
*/ subOb.sum();
// Create a superclass. System.out.println("Total is " + subOb.total);
class A { }
int i; // public by default }
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
A Superclass Variable Can
Reference a Subclass Object
• A reference variable of a superclass can be assigned a reference to
any subclass derived from that superclass.
Using super
• Using super to Call Superclass Constructors
• A Second Use for super
When Constructors Are Called
• Constructors are called in order of derivation, from superclass to
subclass.
• super( ) must be the first statement executed in a subclass’
constructor, this order is the same whether or not super( ) is used.
• If super( ) is not used, then the default or parameterless constructor
of each superclass will be executed.
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
Method Overriding
• In a class hierarchy, when a method in a subclass has the same name
and type signature as a method in its superclass, then the method in
the subclass is said to override the method in the superclass.
• When an overridden method is called from within a subclass, it will
always refer to the version of that method defined by the subclass.
• The version of the method defined by the superclass will be hidden
• Method overriding occurs only when the names and the type
signatures of the two methods are identical.
• If they are not, then the two methods are simply overloaded.
// Method overriding. // display k – this overrides show() in A
class A { void show() {
int i, j; System.out.println("k: " + k);
A(int a, int b) { }
i = a; }
j = b; class Override {
} public static void main(String args[]) {
// display i and j B subOb = new B(1, 2, 3);
void show() { SubOb.show(); // this calls show() in B
System.out.println("i and j: " + i + " " + j); }
} }
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
Use super to call the superclass
methods
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
Dynamic Method Dispatch
• Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
• Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
• Important principle: a superclass reference variable can refer to a
subclass object. Java uses this fact to resolve calls to overridden
methods at run time.
• When an overridden method is called through a superclass reference,
Java determines which version of that method to execute based upon
the type of the object being referred to at the time the call occurs
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
References
Objects
r = a; // r refers to an A object
a Aa A r.callme(); // calls A's version of callme
r = b; // r refers to a B object
b B B A r
c C C
Using Abstract Classes
• Defines a superclass that declares the structure of a given abstraction
without providing a complete implementation of every method.
• Creates 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.
• Such a class determines the nature of the methods that the
subclasses must implement.
Abstract Method
• Are methods defined in the superclass as abstract
• Are methods be overridden by subclasses
• These methods are sometimes referred to as subclasser responsibility
because they have no implementation specified in the superclass.
• General Form:
abstract type name(parameter-list);
Abstract class cont..
• Any class that contains one or more abstract methods must also be
declared abstract.
• To declare a class abstract, you simply use the abstract keyword in front
of the class keyword at the beginning of the class declaration.
• There can be no objects of an abstract class.
• Abstract class cannot be directly instantiated with the new operator.
• An abstract class is not fully defined.
• Abstract constructors, or abstract static methods cannot be declared.
• Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be itself declared abstract.
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();