Java Classes PDF
Java Classes PDF
Declaring Objects
The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Declaring Object
Box mybox = new Box(); This statement combines the two steps. It can be rewritten like this to show each step more clearly:
Box mybox; // declare reference to object and // contains the value null mybox = new Box(); // allocate a Box object
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Constructors
/* Here, Box uses a constructor to initialize the dimensions of a box. */ 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); } }
Parameterized Constructors
/* Here, Box uses a 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 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); } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
Garbage Collection
Since objects are dynamically allocated by using the new operator, how such objects are destroyed and their memory released for later reallocation. In C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
The Java run time calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.
The finalize( ) method ---general form: protected void finalize( ) { // finalization code here }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
It is not called when an object goes out-of-scope, for example. This means that you cannot know whenor even iffinalize( ) will be executed. Therefore, your program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize( )for normal program operation.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
No Destructor in JAVA
C++ allows you to define a destructor for a class, which is
called when an object goes out-of-scope. Java does not support this idea or provide for destructors. The finalize( ) method only approximates the function of a destructor. As you get more experienced with Java, you will see that the need for destructor functions is minimal because of Javas garbage collection subsystem
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Assignment
Overloading Methods
// Demonstrate method overloading. class OverloadDemo { class Overload { void test() { public static void main(String args[]) { System.out.println("No parameters"); OverloadDemo ob = new } OverloadDemo(); // Overload test for one integer parameter. double result; void test(int a) { System.out.println("a: " + a); // call all versions of test() } ob.test(); // Overload test for two integer parameters. ob.test(10); void test(int a, int b) { ob.test(10, 20); System.out.println("a and b: " + a + result = ob.test(123.25); " " + b); System.out.println("Result of } ob.test(123.25): " + result); // overload test for a double parameter } double test(double a) { } System.out.println("double a: " + a); return a*a; } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Output
No parameters a and b: 10 20 Inside test(double) a: 88 Inside test(double) a: 123.2
Note: Java can automatically convert an integer into a double, and this conversion canbe used to resolve the call. Therefore, after test(int) is not found, Java elevates i to double and then calls test(double).
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); }
}
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Output:
ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10 REMEMBER
When a primitive type is passed to a method, it is done by use of call-by-value. Objects are implicitly passed by use of call-byreference.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Returning Objects
// Returning an object. class RetOb { class Test { public static void main(String args[]) { int a; Test ob1 = new Test(2); Test(int i) { Test ob2; a = i; ob2 = ob1.incrByTen(); } System.out.println("ob1.a: " + Test incrByTen() { ob1.a); Test temp = new System.out.println("ob2.a: " + Test(a+10); ob2.a); return temp; ob2 = ob2.incrByTen(); } System.out.println("ob2.a after } second increase: + ob2.a); } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
output
ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22
Important
Since all objects are dynamically allocated using new, you dont need to worry about an object going out-of-scope because the method in which it was created terminates. The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time H.K.Vedamurthy,Asst garbage collection takes place. Professor, Dept of CSE,SIT,Tumkur
Access Control
Javas access specifiers are public, private, and protected. In the classes, all members of a class have used the default access mode, which is essentially public
Now you can understand why main( )has always been preceded by the public specifier. It is called by code that is outside the programthat is, by the Java run-time system. When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. A package is, essentially, a grouping of classes.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Access Control
/* This program demonstrates the difference between public and private. */ class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) { // set c's value c = i; } int getc() { // get c's value return c; } }
class AccessTest { public static void main(String args[]) { Test ob = new Test();
// These are OK, a and b may be // accessed directly
ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Understanding static
Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, 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.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Static Block
// 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); } H.K.Vedamurthy,Asst Professor, Dept of } CSE,SIT,Tumkur
Output:
Static block initialized. x = 42 a=3 b = 12
Static Member
class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Introducing final
A variable can be declared as final. Doing so prevents its contents from being modified.
Example:
final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5;
This means that you must initialize a final variable when it is declared. Subsequent parts of your program can now use FILE_OPEN, etc., as if they were constants, without fear that a value has been changed.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
System.out.println("Stack is full.");
int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } } //end of stack class
for(int i=0; i<5; i++) mystack1.push(i); for(int i=0; i<8; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:"); for(int i=0; i<5; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<8; i++) System.out.println(mystack2.pop()); }
Inner class Example// Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Output: display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100 display: outer_x = 100
The first thing to understand about strings is that every string you create is actually an object of type String.
Even string constants are actually String objects. For example, in the statement System.out.println("This is a String, too"); the string This is a String, too is a String constant.
The second thing to understand about strings is that objects of type String are immutable; once a String object is created, its contents cannot be altered.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Strings can be constructed like this: String myString = "this is a test"; Java defines one operator for String objects: +. It is used to concatenate two strings.
For example,
String myString = "I" + " like " + "Java."; results in myString containing I like Java.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Demonstrating Strings.
class StringDemo { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1 + " and " + strOb2; System.out.println(strOb1); System.out.println(strOb2); System.out.println(strOb3); } }
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
Output: First String Second String First String and Second String
methods that need to take a variable number of arguments. This feature is called varargs and it is short for variable-length arguments.
A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method. A variable-length argument is specified by three periods (...). For example
Variable-length arguments
A method can have normal parameters along with a variablelength parameter. However, the. For example, variable-length parameter must be the last parameter declared by the method
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
Here, there is an attempt to declare a regular parameter after H.K.Vedamurthy,Asst the varargs parameter, which is Professor, Dept of illegal. CSE,SIT,Tumkur
Variable-length arguments
There is one more restriction to be aware of: there must be only one varargs parameter.
int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error! The attempt to declare the second varargs parameter is illegal.
public static void main(String args[]) { vaTest(1, 2, 3); vaTest("Testing: ", 10, 20); vaTest(true, false, false); } }
Output: vaTest(int ...): Number of args: 3 Contents: 1 2 3 vaTest(String, int ...): Testing: 2 Contents: 10 20 vaTest(boolean ...) Number of args: 3 Contents: true false false H.K.Vedamurthy,Asst Professor, Dept of
CSE,SIT,Tumkur
NOTE : A varargs method can also be overloaded by a nonvarargs method. For example, vaTest(int x) is a valid overload of vaTest( ) in the foregoing program. This version is invoked only when one int argument is present.
When two or more int arguments are passed, the varargs version vaTest(intv) is used.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
class VarArgs4 {
In this program, the overloading ofvaTest( ) is perfectly correct. However, this program will not compile because of the following call: vaTest(); // Error: Ambiguous! Because the vararg parameter can be empty, this call could be translated into a call to vaTest(int ...) or vaTest(boolean ...). Both are equally valid. Thus, the call is inherently ambiguous. Here is another example of ambiguity. The following overloaded versions of vaTest( ) are inherently ambiguous even though one takes a normal parameter: static void vaTest(int ... v) { // ... static void vaTest(int n, int ... v) { // ...
Although the parameter lists of vaTest( ) differ, there is no way for the compiler to resolve the following call:
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur
vaTest(1)
vaTest(1)
Does this translate into a call to vaTest(int ...), With one varargs argument, or into a call to a Test(int, int ...) with no varargs arguments? There is no way for the compiler to answer this question. Thus, the situation is ambiguous.
H.K.Vedamurthy,Asst Professor, Dept of CSE,SIT,Tumkur