Professional Documents
Culture Documents
1
Class Fundamentals
• It defines a new data type
2
The General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
3
• Collectively, the methods and variables
defined within a class are called members of
the class
4
Access Modifiers In Java
Class level access modifiers (java classes only)
•Only two access modifiers is allowed, public
and no modifier
•If a class is ‘public’, then it CAN be accessed
from ANYWHERE.
•If a class has ‘no modifer’, then it CAN ONLY be
accessed from ‘same package’
5
Member level access modifiers (java variables and java methods)
All the four public, private, protected and no modifer is allowed.
public and no modifier – the same way as used in class level.
private – members CAN ONLY access.
protected – CAN be accessed from ‘same package’ and a subclass existing in any
package can access.
For better understanding, member level access is formulated as a table:
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N
A Simple Class
class Box {
double width;
double height;
double depth;
}
7
• To access these variables, you will use the dot
(.) operator
Example:
mybox.width = 100;
8
class Box {
double width;
double height;
double depth;
} // This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15; // compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
} 9
• When you compile this program, you will find
that two .class files have been created, one
for Box and one for BoxDemo
10
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance
variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15; 11
/*assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
12
Declaring Objects
• First, you must declare a variable of the class type
13
• The new operator dynamically allocates
memory for an object and returns a reference
to it
14
Assigning Object Reference Variables
Example:
Box b1 = new Box();
Box b2 = b1;
16
17
• Although b1 and b2 both refer to the same
object, they are not linked in any other way
Example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
19
Introducing Methods
type name(parameter-list) {
// body of method
}
27
• Box uses a constructor to initialize dimensions
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;
}
} 28
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);
}
}
29
Consider
Box mybox1 = new Box();
31
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);
}
}
32
The this Keyword
• this can be used inside any method to refer to the
current object
Example:
Box(double w, double h, double d) {
this.width = w; //The use of this is redundant,
this.height = h; //but perfectly correct
this.depth = d;
}
33
Instance variable hiding
• It is illegal in java to declare two local variables with the same name inside
the same or enclosing scopes.
• Interestingly, you can have local variables, including formal parameters to
methods, which overlap with the names of the class instance variables. We
can see the following example for this explanation.
Example:
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
34
• However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable. This is why width, height, and depth were not
used as the names for the parameters to the Box() constructor inside the Box class. If
they had been, then width would have referred to the formal parameter, hiding the
instance variable width.
Example:
Box(double width, double h, double d) {
width = width; \\width refers to formal parameter
height = h;
depth = d;
}
35
• While it is usually easier to simply use different names, there is
another way around this situation. Because this lets you refer directly
to the object, you can use it to resolve any name space collisions that
might occur between instance variables and local variables.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
36
Garbage Collection
• In some languages, such as C++, dynamically
allocated objects must be manually released by use
of a delete operator
37
Contd..
• When no references to an object exist, that
object is assumed to be no longer needed,
and the memory occupied by the object can
be reclaimed
38
The finalize( ) Method
• Sometimes an object will need to perform
some action when it is destroyed
39
• By using finalization, you can define specific
actions that will occur when an object is just
about to be reclaimed by the garbage collector
40
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
41
• It is important to understand that finalize( ) is only
called just prior to garbage collection
44
// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
}
}
45
Local variables:
Local variables are declared in methods, constructors, or
blocks.
Local variables are created when the method, constructor or
block is entered and the variable will be destroyed once it exits
the method, constructor or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method,
constructor or block.
Local variables are implemented at stack level internally.
There is no default value for local variables so local variables
name inside the class. However within static methods and different
class ( when instance variables are given accessibility) should be
called using the fully qualified name . ObjectReference.VariableName.
Instance variables:
class Employee{
public String name;
private double salary;
public Employee (String empName){
name = empName; }
public void setSalary(double empSal){
salary = empSal; }
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary); }
public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp(); } }
Overloading Methods
• In Java it is possible to define two or more methods
within the same class that share the same name, as
long as their parameter declarations are different
50
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
51
double test(double a) {
System.out.println("double a: " + a);
return a*a;
} }
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result; // call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " +
result);
}
} 52
• In some cases Java’s automatic type
conversions can play a role in overload
resolution
53
// Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
54
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); //this will invoke test(double)
}
}
55
This program generates the following output:
No parameters
a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
56
Overloading Constructors
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
57
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
} // compute and return volume
double volume() {
return width * height * depth;
}
} 58
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " +
vol);
// get volume of second box
vol = mybox2.volume();
59
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
• Call by value
• Call by reference
63
Contd..
• when you pass a simple type to a method, it is
passed by value
71
/* 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;
}
}
72
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
//ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
73
Understanding 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
classname.method( )
79
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);
} }
Here is the output of this program:
a = 42
b = 99 80
Introducing final
• A variable can be declared as final
81
• Variables declared as final do not occupy
memory on a per-instance basis
82
Arrays Revisited
• Implemented as objects
85
// push some numbers onto the stack
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());
}
}
Using Command-Line Arguments
87
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]:"+args[i]);
}
}
Execution:
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1 88