Beruflich Dokumente
Kultur Dokumente
Operations/Methods
Class BankAccount MakeDesposit
Balance Transfer
Interest
WithDraw
Owner
Account_number GetBalance
K. Lakshmi Narayana 3
KLN Classes and Objects
Classes
The class defines a new data type, this new type can be used to
create objects of that type.
All the java statements, method definitions and method calls are
inside the class only including main method.
K. Lakshmi Narayana 4
KLN Classes and Objects
Objects
An object is an instance of a class.
The process of creating objects from a class is called instantiation.
Objects enhance software reusability. Once a class is defined, we can
create any number of objects of the same type.
C++ objects can be created with class name followed by an
object name.
In Java we can create an object with the reference and new
operator (Java reference is not same as C++ reference).
K. Lakshmi Narayana 7
KLN Classes and Objects
Java Object Creation
Obtaining an object of a class in Java is a two-step process.
First you must create a reference variable of the class type.
Second you must acquire actual, physical copy of the object and assign it
to that reference variable. This can be done by using new operator.
The operator new creates a new object of the class specified to the right of the keyword.
Box mybox; mybox
null width
mybox=new Box(); height
mybox
depth
Box Object
The first line declares mybox as a reference type. After this line executes, mybox
contains the null value, which indicates it does not point to any object. Any
attempt to use mybox results in a compile error. The next line allocates an actual
object and assigns a reference to it to mybox. Now you can use mybox as Box object.
When you are executing a java program then JVM executes two
memory blocks for program execution.
K. Lakshmi Narayana 11
KLN Classes and Objects
Life Cycle of Objects
K. Lakshmi Narayana 12
KLN Classes and Objects
K. Lakshmi Narayana 13
KLN Classes and Objects
Life Cycle of Objects
Stack HEAP
Sample x ;
x = new Sample(); x 1 reference
1 reference
K. Lakshmi Narayana 14
KLN Classes and Objects
K. Lakshmi Narayana 15
KLN Classes and Objects
z = y;
K. Lakshmi Narayana 16
KLN Classes and Objects
K. Lakshmi Narayana 17
KLN Classes and Objects
Life Cycle of Objects
Stack HEAP
Sample x ;
x = new Sample(); z
x 0 references
Sample y = new Sample(); (eligible for GC)
Sample z= x; y 1 reference
z = y;
x = null; 2 references
x = new Sample();
K. Lakshmi Narayana 18
KLN Classes and Objects
z = y;
x = null;
x = new Sample(); 0 references
(eligible for GC)
z=null;
y=null;
K. Lakshmi Narayana 19
KLN Method Declarations Classes and Objects
Syntax:
<method modifiers> <formal parameter list> <return
type> <method name>
(<formal parameter list>) <throws clause> // Method header
{ // Method body
<local variable declarations>
<nested local class declarations>
<statements>
}
The method header can specify the following information:
• Method modifiers are private, protected, public or default.
• Additional method modifiers(i.e. static, final, abstract, synchronized, strictfp, native,
annotation, transient, and volatile)
• A formal parameter list is a comma-separated list of parameters, where each
parameter is a simple variable declaration consisting of its type and name.
<parameter modifier> <type> <parameter name>
• checked exceptions thrown by the method are specified in a throws clause
K. Lakshmi Narayana 20
20
KLN Classes and Objects
Accessing Object Members
The “dot” notation: <object> • <member>
This is used to access object members including attributes and methods
Example:
// Accessing the member variables through member functions
obj1.setX(2912);
// Accessing the member variables directly if x is public
obj1.y = 2912;
// Accessing the methods
obj1.display();
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 to garbage collection.
K. Lakshmi Narayana 21
KLN Classes and Objects
Access Modifiers
public keyword
All the classes, member variables and methods declared with this
keyword are accessible to other classes and other packages.
A public class, variable or method may be used in any program without
restriction.
protected keyword
All the member variables and methods declared with this keyword
are accessible to all the classes in the same package and to subclasses
of that class within the same or other packages.
Also available to all sub-classes of the class that owns the protected
feature.
Only variables and methods may be declared protected.
K. Lakshmi Narayana 22
KLN Classes and Objects
Access Modifiers
Package Access Modifier
It is the name of access types of class, variable and method if you do
not specify any access modifiers. It allows accessibility to any class in
the same package.
private keyword
All the member variables and methods declared with this keyword
are accessible to it’s own class only i.e., specifying a member as
private makes it not accessible to any other classes.
If you want to access the methods from outside the class don’t keep
it in private section.
default
All classes inside the same package
and derived classes of any package.
protected
Any classes
package kln.scjp;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package kln.java.cse;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package kln;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
K. Lakshmi Narayana 26
KLN Classes and Objects
Protected Access Modifier
public class A {
protected int x;
}
public class E {
void foo(A a) { this.x; a.x; } // ERROR, E is NOT a decendent of A
}
K. Lakshmi Narayana 27
KLN Classes and Objects
Access Modifier Example i = 10, j = 20, and k = 30
class A Value of j = 50
{ private int i=10; public int j=20;
Value of k = 100
int k=30;
public void print()
{ System.out.println("i = " +i+", j = " +j+", and k = " +k);
}
}
class AccessModifiers
{ public static void main(String[] args)
{ A a1=new A();
//a1.i=50; //Private members cannot be accessed
a1.print();
a1.j=50; a1.k=100;
System.out.println("\nValue of j = " +a1.j);
System.out.println("\nValue of k = " +a1.k);
}
}
K. Lakshmi Narayana 28
KLN Default, public and private modifiers Classes and Objects
class Test {
int a; // default access
public int b; // public access
private int c; // private access
void setc(int i) { c = I; } // methods to access c
int getc() { return c; } // get c's value
}
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;
// ob.c = 100; // Error!
ob.setc(100); // Access member c with methods is OK
System.out.println("a, b, and c: “+ob.a+" “+ob.b+" "+ ob.getc());
}
}
K. Lakshmi Narayana
a, b, and c: 10 20 100
29
KLN Classes and Objects
Accessibility Criteria
Default
Private Protected Public
No Modifier
Different Package
NO NO YES YES
Derived class
Different Package
NO NO NO YES
Non-Derived class
K. Lakshmi Narayana 30
KLN Classes and Objects
Rectangle Class without using Methods
import java.util.*;
class Rectangle
{ private int l, b;
public static void main(String args[])
{ Rectangle r1 = new Rectangle();
Scanner sc=new Scanner(System.in);
System.out.print("Enter the r1 Length and Width :: ");
r1.l= sc.nextInt(); r1.b= sc.nextInt();
System.out.println("Area = " + r1.l * r1.b);
System.out.println("Perimeter = " + 2*(r1.l+r1.b));
}
}
K. Lakshmi Narayana 31
KLN Classes and Objects
Rectangle Class with Methods Ver-1
class Rectangle
{ private int len, width;
private Rectangle(int x, int y){ len=x; width=y; } //Constructor
private int area(){ return (len*width); }
private int per(){ return 2*(len+width); }
public static void main(String args[])
{ Rectangle r = new Rectangle(10, 8);
System.out.println("Perimeter = " + r.area());
System.out.println("Perimeter = " + r.per());
}
}
K. Lakshmi Narayana 32
KLN Classes and Objects
Rectangle Class with Methods Ver-2
1) In java we can define more than one class.
2) We can define at most one public class.
3) If java file is having a public class then filename must be the
same as that public class name.
class Rectangle
{ private int len, width;
Rectangle(int x,int y){ len=x;width=y; }
int area(){ return (len*width); }
int per(){ return 2*(len+width); }
}
class MyRectangle
{ public static void main(String args[])
{ Rectangle r = new Rectangle(10, 5);
System.out.println("Perimeter = " + r.area());
System.out.println("Perimeter = " + r.per());
}
K.}Lakshmi Narayana 33
KLN Classes and Objects
Rectangle Class with Methods Ver-3
class Rectangle
{ private int len, width;
Rectangle(int x,int y){ len=x;width=y; }
int area(){ return (len*width); }
Rectangle.java
int per(){ return 2*(len+width); }
}
class MyRectangle
{ public static void main(String args[])
MyRectangle.java
{ Rectangle r = new Rectangle(10, 5);
System.out.println("Perimeter = " + r.area());
System.out.println("Perimeter = " + r.per());
}
}
K. Lakshmi Narayana 34
KLN Rectangle Class in different packages Ver-4
Classes and Objects
package kln.r1;
public class Rectangle
{ private int len, width;
public Rectangle(int x,int y){ len=x;width=y; }
public int area(){ return (len*width); } Rectangle.java
public int per(){ return 2*(len+width); }
}
package kln.r2;
import kln.r1.*;
class MyRectangle MyRectangle.java
{ public static void main(String args[])
{ Rectangle r = new Rectangle(12, 8);
System.out.println("Area = " + r.area());
System.out.println("Perimeter = " + r.per());
}
}
K. Lakshmi Narayana 35
KLN Classes and Objects
Print the Date in dd/mm/yyyy format
import java.util.*;
public class Today
{ public static void main (String[] args)
{ Date d=new Date();
System.out.println("Today\'s Date : " +d.getDate()
+"/"+(d.getMonth()+1)+ "/"+(d.getYear()+1900));
System.out.println("Time : " +d.getHours()
+":"+d.getMinutes());
}
}
K. Lakshmi Narayana 36
KLN Classes and Objects
K. Lakshmi Narayana 37
KLN Classes and Objects
Random class Example1
Declaring Constructors
Syntax:
<accessibility modifier> <class name> (<formal parameter list>)
<throws clause> // Constructor header
The default return type of the
{ // Constructor body
constructor is the object of that class
<local variable declarations> type. Where as methods doesn’t
<nested local class declarations> have any default return types.
<statements>
}
Rules of Constructor:
The constructor name must be the same as the class name.
It can not have any return type, not even void. The implicit return
constructor.
K. Lakshmi Narayana 40
KLN Classes and Objects
Constructor Example
By default constructor return type is object type of that
class Rectangle class. So we no need to keep explicit return type.
{
double len, width;
Rectangle(double l,double w){ len=l;width=w; }
void printArea()
{ System.out.println("Area of the Rectangle = "+len*width); }
}
class MyRectangle
{
public static void main(String args[])
{ //Rectangle r1=new Rectangle(); //ERROR Default constructor not present
Rectangle r = new Rectangle(2.0,3.0); //constructor
System.out.println("Rectangle Length="+r.len+"and Width="+r.width);
r.printArea();
} Rectangle Length = 2.0 and Width = 3.0
} Lakshmi Narayana
K. Area of the Rectangle = 6.0 41
KLN Classes and Objects
Use of this reference
When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
Use the keyword this to overcome the instance variable hiding.
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.
This reference can be used to access data members of the current object
on which the method is invoked.
If we use a data member name inside a method then it is converted as
this.DataMemeberName.
class Rectangle
{ int len, width;
Rectangle(int len, int width)
{ this.len=len;
this.width=width;
}
void print( )
{ System.out.println("Length :: "+len+", and Width :: "+ this.width);
}
}
public class MyRectangle
{ public static void main(String arg[])
{ Rectangle r1=new Rectangle(8,6);
r1.print();
}
} Lakshmi Narayana
K. 44
44
KLN Classes and Objects
Constructor overloading
Constructors can also be overloaded similarly as method overloading. So a
class can have N number of constructors using overloading.
Example:
public class Rectangle{
double length=5.6, width;
Rectangle() { }
Rectangle(double length,double width){ this.length=length;
this.width=width; }
void print( ) { System.out.println("length= " + length + ", and width= "+ width); }
public static void main(String [] args)
{ Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle(10, 8);
r1.print(); r2.print();
}
}
K. Lakshmi Narayana 45
KLN Classes and Objects
Copy Constructor
Sometimes a programmer wants to create an exact but separate copy of
an existing object so that subsequent changes to the copy should not
alter the original or vice versa. This is possible by copy constructor.
K. Lakshmi Narayana 46
KLN Classes and Objects
Copy Constructor Example
class Rectangle
{ int l, b;
Rectangle(int x, int y) { l=x; b=y; }
void setRect(int x, int y) { l=x; b=y; }
Rectangle(Rectangle obj) //copy constructor
{ System.out.println("Copy Constructor Invoked");
l = obj.l; b = obj.b;
}
int area() { return (l * b); }
}
class CopyConstructor
{ public static void main(String[] args)
{ Rectangle r1 = new Rectangle(8,5);
Rectangle r2= new Rectangle(r1); r1.setRect(10, 6);
System.out.println("Area of First Rectangle : "+ r1.area());
System .out.println("Area of Second Rectangle : "+ r2.area());
}
K. Lakshmi Narayana 47
}
KLN Classes and Objects
Static/class Fields
There is only one copy of the static field for the whole class, and it can be
shared by all the objects of the class, they are also know as class variables,
whereas instance variables are separate copy with each object.
static variables can be accessed directly, through class, and through object
<static_var>
<classname>.< static_var >
<objectname>.< static_var >
Static methods
K. Lakshmi Narayana 52
KLN Static variables and methods Classes and Objects
class Sample
{ static int x=5; int y=10;
void welcome() { System.out.println("It is for B.Tech ECE "); }
static void bestWishes()
{ System.out.println("\nThank you for Choosing JAVA Course");
}
public void printValues( )
{ System.out.println("x = " + x + ", and y = " + y);
}
public static void main(String arg[]) throws Exception
{ Sample s=new Sample(); //Object is created
System.out.println("x = " + x);
System.out.println("x = " + s.x);
System.out.println("Through class reference x = " + Sample.x);
System.out.println("y = " + s.y);
K. Lakshmi Narayana 53
KLN Static variables and methods Classes and Objects
K. Lakshmi Narayana 54
KLN Addition of Two Matrices Classes and Objects
import java.util.*;
class MatrixAddition
{ int mat[][]; int rows,cols;
public MatrixAddition() { }
public MatrixAddition(int r, int c)
{ rows=r; cols=c;
mat=new int[rows][cols];
}
public void read()
{ int i, j;
Scanner sc=new Scanner(System.in);
for(i=0;i<rows;i++)
for(j=0;j<cols;j++)
mat[i][j]=sc.nextInt();
}
public void display()
{ int i, j;
for(i=0;i<rows;i++)
{ for(j=0;j<cols;j++)
System.out.print(" "+ mat[i][j]);
System.out.println();
}
K. Lakshmi
} Narayana 55
KLN Addition of Two Matrices Cont.. Classes and Objects
import java.util.*;
class MatrixTranspose
{ int mat[][]; int r,c;
public MatrixTranspose() { }
public MatrixTranspose(int r, int c){ this.r=r; this.c=c; mat=new int[r][c]; }
public void read()
{ int i, j; Scanner sc=new Scanner(System.in);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
mat[i][j]=sc.nextInt();
}
public void display()
{ int i, j;
for(i=0;i<r;i++)
{ for(j=0;j<c;j++)
System.out.print(" "+ mat[i][j]);
System.out.println();
}
}
K. Lakshmi Narayana 59
KLN Classes and Objects
Transpose of a Matrix cont…
public MatrixTranspose transpose(MatrixTranspose m)
{ MatrixTranspose temp=new MatrixTranspose(m.c, m.r); int i, j;
for(i=0; i<m.c; i++)
for(j=0; j<m.r; j++)
temp.mat[i][j] = m.mat[j][i];
return temp;
}
public static void main(String [] args)
{ MatrixTranspose m1=new MatrixTranspose(3, 4);
MatrixTranspose m2;
System.out.println("Enter the elements of 3X4 Matrix"); m1.read();
m2=m1.transpose(m1);
System.out.println("Original Matrix ::"); m1.display();
System.out.println();
System.out.println("Transpose of Matrix ::"); m2.display();
}
K.}Lakshmi Narayana 60
KLN Design a Student class with roll, name, Classes and Objects
5 subjects
import java.util.*;
class Student
{ int roll; String name;
double marks[] = new double[5];
Student(int r, String n)
{ roll=r; name=n;
}
void readMarks()
{ Scanner sc=new Scanner(System.in);
for(int i=0; i<5; i++)
marks[i]=sc.nextInt();
}
void printStudent()
{ System.out.print("Roll " + roll);
System.out.print(", Name " + name);
System.out.println(", Grade :: " + grade());
}
K. Lakshmi Narayana 61
KLN Design a Student class with roll, name, Classes and Objects
5 subjects
String grade()
{ double total=0, avg;
for(int i=0; i<5; i++)
total +=marks[i];
avg=total/5;
if(avg>=60) return "First";
if(avg>=50) return "Second";
if(avg>=40) return "Third";
else return "Fail";
}
public static void main(String ar[])
{ Student s1=new Student(406, "Ram Lal");
System.out.print("Enter 5 Subjects marks :: ");
s1.readMarks();
s1.printStudent();
}
}
K. Lakshmi Narayana 62
KLN Sort Student Objects in ascending orderClasses and Objects
of marks
import java.util.*;
class Student
{ int roll; String name; float marks;
Student(int roll, String name, float marks)
{ this.roll=roll; this.name=name; this.marks=marks;
}
public String toString() //toString method is overloaded
{ return ("Student Roll No :: "+ roll +", Name :: "+ name +", and Marks :: "+ marks + "\n");
}
public static void main(String ar[])
{ int r; String nm; float m; int n;
Scanner key=new Scanner(System.in);
System.out.print("Enter the Number of Students :: ");
n=key.nextInt(); Student s[ ]=new Student[n];
for(int i=0; i<n; i++)
{ System.out.print("Enter the Roll Number :: "); r=key.nextInt();
System.out.print("Enter the Name :: "); nm=key.next();
System.out.print("Enter the Marks :: "); m=key.nextFloat();
s[i]=new Student(r, nm, m);
} Narayana
K. Lakshmi 63
KLN Sort Student Objects in ascending orderClasses and Objects
of marks
K. Lakshmi Narayana 65
KLN Classes and Objects
Things to Remember
Top level classes and interfaces must have default or public accessibility.
transient modifier not applicable to static variables.
volatile - variable should not be cached by the threads. Threads use local caching
to increase speed. volatile prevents this to support possible loss of integrity.
for each try block - 0 or more catch block, 0 or 1 finally block, must have at least 1
catch block or 1 finally block.
Interface methods - public and abstract by default
Interface constants - public static final by default
(null instanceof X) always false for any class X.
explicit calls for gc - System.gc() OR System.runFinalization()
Class Initialization sequence (1) superclass is initiated
(2) static initialization blocks are executed.
Object Initialization sequence
(1) Instance variables set to defaults
(2) call chain of constructors
(3) last constructor creates object super object
(4) instance initialization expressions and blocks executed in order of appearance
static methods can be synchronized
lock for class static methods is different from lock of object of class.
Wrapper class Void is not instantiable
K. Lakshmi Narayana 66
66
KLN Classes and Objects
Thank You
K. Lakshmi Narayana