Java Classes and Objects
Shakir Hussain
Will cover
Memory Structure
Writing java class with
◦ instance variables & members
◦ Reference variables
◦ Method overloading
◦ “this” reference
Writing java class with
◦ Constructors
Static variables & methods
Arrays
Packages
Access Specifier
Static Import
Introduction to Eclipse IDE for Java development
2
Memory Structure
Stack Area Local Variables
Movable Boundary
Heap Area Dynamically allocated Area
Fixed Boundary
Data Area Static Variables
Code Section
3
Reference data types
Primitive data types are built in.
array & user defined datatypes are reference
Key difference between primitive and
reference datatypes is how they are
represented.
Primitive type variable hold the actual value
of the variable
Reference type variable hold the value of a
reference to the object.
4
Method overloading
Reusingthe same name for a method.
Arguments should be different.
◦ Type of arguments
◦ Number of arguments
◦ Order of arguments
The method calls are resolved at compile
time using the method signature.
Compile time error occurs if compiler can’t
match the arguments or if more than one
match is possible.
5
“this” reference
Every class member gets a hidden parameter :
the this reference.
this is a keyword in Java.
this points to the current object.
this always holds address of an object which is
invoking the member method.
It is often a logic error when a method contains
a parameter or local variable that has the same
name as a field of the class. In this case use this
reference if you wish to access the field of the
class- otherwise a method parameter or local
variable will be referenced
6
Constructor
class Emp {
private int empId;
private String empName;
Emp() {} //default constructor
Emp(int id, String name) //parameterized constuctor
{empId=id; this.empName=name;}
public void displayEmpDetails(){
SOP(“empId=“+empId); SOP(“empName=“+empName);
}
}
7
Constructor …
Used to initialize the data members of the class
Special method with same name as it’s class name
No return type for constructor. Not even void
Constructors are implicitly called when objects are
created
By default, the compiler provides a default
constructor with no parameters in any class that does
not explicitly include a constructor
Constructors can be overloaded
No destructor in java.
8
Static variable
Only single copy exists per class
It’s a class variable
Can be accessed outside of its class
through the use of the class name.
Can be accessed from inside any member
class method with or without the class
name.
9
Static variables in Memory
e1 e2 e3
empId empId empId
empName empName empName
deptName deptName deptName
count
10
Static Member methods
Static
member methods can access static data
members only.
Static member method is invoked using class
name
class name . method name()
Referencethis is never passed to a static
member function
11
Static block
Static block can be used to initialized
static data members
Static block executes as soon as the class
loaded in the memory.
12
Variables in java
Class variables: Static variables. Copy
created per class.
Instance variables : Copy created per
instance of the class.
Local variables: occur within methods or
blocks: Copy created per method call.
If used, must be initialized or the compiler
complains.
13
Arrays
An array is a list of similar things
An array has a fixed:
◦ name
◦ type
◦ length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution of
the code
14
myArray = 3 6 3 1 6 3 4 1
0 1 2 3 4 5 6 7
myArray has room for 8 elements
the elements are accessed by their index
in Java, array indices start at 0
15
Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory,
labelled myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
16
Assigning Values
refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
int myArray[]=new int[]{10,20,30};
17
Iterating Through Arrays
for loops are useful when dealing with arrays:
for (int i=0;i<myArray.length; i++){
System.out.println(myArray[i]);
}
18
Arrays of Objects
So far we have looked at an array of primitive types.
◦ integers
◦ could also use doubles, floats, characters…
Often want to have an array of objects
◦ Students, Books, Loans ……
Need to follow 3 steps.
19
Array of Objects ...
1. Declare the array
private Student studentList[];
◦ this declares studentList
2 .Create the array
studentList = new Student[10];
◦ this sets up 10 spaces in memory that can
hold references to Student objects
3. Create Student objects and add them to the array:
studentList[0] = new Student("Cathy",
"Computing");
20
Multi-Dimensional Array
Array of arrays :
int twoDim[][]=new int[2][];
twoDim[0]=new int[2];
twoDim[1]=new int[5];
int twoDim[][]=new int[][2]; // illegal
int twoDim[][]=new int[2][2]; // legal
Can have non-rectangular array
21
Array Resizing
Can not resize an array.
Can use the same reference variable to
refer to an entirely new array
int elements[]=new int[10];
elements=new int[20];
22
Arrays: First class object
Arrays are first class objects in Java.
◦ int arr[ ] ;
arr = new int[10];
◦ int arr[ ] = {10, 20, 30, 40, 50}; //first class object
Array references are stored on stack.
The actual array is created on heap.
23
Packages
Used to group related classes and
interfaces.
Convenient for organizing your work &
separating your work from code libraries
provided by others
Reduce problems with naming conflicts
Classes with same name can be put into
different packages
24
Creating package
Writea package statement at the top of the source file in
which the type(class or interface) is defined
package pkg;
public class Emp {
}
Create a subdirectory of that package name. Compile the file and
keep the .class files in the directory.
Alternatively, you can directly compile like:
javac –d . Emp.java
Here, the compiler will create directory structure for you.
25
Using package
import pkg.*;
class EmpTest{
public static void main(String args[]){
Emp e = new Emp();
pkg.Emp e2=new pkg.Emp();
}
}
Import statement imports all the public classes
within the package; it does not import sub
packages.
26
Finding Packages and
CLASSPATH
How does the Java run-time system know where to
look for packages that you create?
Packages are like directories.
You can specify a directory path or paths by setting
the CLASSPATH environmental variable
27
CLASSPATH
For java to be able to use a class, it has to
be able to find that class on the file
system.
Java uses 2 elements to find classes
◦ The package name
◦ The directories listed in CLASSPATH variable
28
How Compiler/JVM locates a File
Check current directory.
Compiler
looks through all directories specified in the
CLASSPATH for
the actual class file
OR
the subdirectory that has the name of the imported package.
Then, looks for the file in one of the imported packages.
Finally looks for file in java.lang package.
If compiler still does not locate the file, it gives an error.
29
Access Specifiers
private
Package-level (default, if not specified)
protected
Public
Either
four can be applied to class
members(variable or function)
Only, Package-Level & public allowed for
class.
30
Access Modifier example
Create a package having a class , which
will hold
public, private,default,protected members
(field & methods)
Create another package having Test class
which will access above package and
class members
Which members you will be able to call ?
31
Static Import
Startingwith JDK 5.0, the import statement has
been enhanced to permit the importing of static
methods and fields, not just classes.
For example if you add the directive
import static java.lang.System.*;
to the top of the source file, then you can use static
methods and fields of the System class without the
class name prefix – for e.g.
out.println(“Hello World”);
You can also import a specific method or a field
import static java.lang.System.out;
32
Static Import : Precaution
Makes the code confusing to read
It can create naming conflicts.
For example, if you have two different
classes with an “add()” method, how will
you and the compiler know which one to
use?
33
Introduction to eclipse IDE
for Java Development
34
35