0% found this document useful (0 votes)
30 views

Classes & Objects

JAVA

Uploaded by

REESHU RANJAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Classes & Objects

JAVA

Uploaded by

REESHU RANJAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Java Programming(19IS503)

Module 2
Introducing Classes Objects & Methods

Course Faculty
Dr.Chandrika.J
Professor & Head
ISE
Module 2 Syllabus
• Introducing Classes, Objects and Methods: Class Fundamentals,
Declaring Objects, Object Reference Variables, Methods,
Constructors, The this keyword, Garbage collection, Overloading
Methods and constructors, Argument Passing, Returning Objects,
Recursion, Access Control, Nested and Inner Classes.
• Inheritance, Packages and Interfaces: Inheritance Basics, Using Super,
Multilevel Hierarchy, When Constructors are called, Method
Overriding, Abstract Classes. Packages, Access Protection, Importing
Packages, Interfaces.
Class Fundamentals(23-11-2021)
• A class is a template that defines the form of an object.

• It specifies both the data and the code that will operate on that data.

• Java uses a class specification to construct objects.

• Objects are instances of a class.

• The methods and variables that constitute a class are called members of the
class. The data members are also referred to as instance variables.

• Through Class data encapsulation is achieved


General form of a class
Class classname { A Simple class
Type instance-var1; class Box {
Type instance-var2;
double width;
.....;
type methodname1(parameter-list) { double height;
// body of method double depth;
}
}
type methodname2(parameter-list) {
// body of method To create a Box object,
} Box B = new Box();
................
To access the variables of the box object, dot operator
}
is required.
Dot operator links the name of the object with the
name of an instance variable.
E.g., to assign width of mybox to 100 B.width = 100;
Example Program
class Box {
double width; double height; double depth;
}

class Boxdemo1
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println(“Volume is “ + vol);
}
}
Number of classes?
Output : Volume is 3000.0 Number of instance variables?
Number of objects/instances?
Identify type conversion
Identify type casting
Observe Indentation
Example Program –Declaring 2 objects
class Box {
double width; double height; double depth;
}
class Boxdemo2{
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox 2= new Box();
double vol;

mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15;


mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9;

vol = mybox1.width * mybox1.height * mybox1.depth;


S.o.p(“Volume is “ + vol);

vol = mybox2.width * mybox2.height * mybox2.depth;


S.o.p(“Volume is “ + vol);

}
}
Output : Volume is 3000.0
Volume is 162.0
Declaring Objects

• Box mybox = new Box();


• Box mybox;
mybox = new Box();
• New allocates memory for an object during run time.
• The advantage is that the program can create as many or as few objects as it
needs during the execution of the program.
• If insufficient memory then, runtime exception occurs.
Assigning Object Reference Variables

• Box b1 = new Box();


Box b2 = b1;
• Here b1 and b2 refer to the same
object.
• The assignment of b1 to b2 does not
allocate any memory or copy any
part of the original object.
• That is b2 refers to the same object
as does b1.
• Any changes made to the object
through b2 will affect the object to
which b1 is referring.
Introducing Methods (24-11-2021)
class Box {
double width;
double height;
double depth;
void volume() {
System.out.print("volume is");
System.out.println(width * height * depth);
}
}
class Boxdemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();

mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15;

mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9;

mybox1.volume();
mybox2.volume();
}
}
Returning a Value
class Box {
double width; double height; double depth;
double volume() {
return width * height * depth;
}
}
class Boxdemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15;


mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9;

vol = mybox1.volume();
System.out.println(“Volume is “ + vol);

mybox2.volume();
System.out.println(“Volume is “ + vol);
}
}
Adding a method that takes Parameters
class Box {
double width; double height; double depth;
double volume() {
return width * height * depth;
}
void setdim(double w, double h, double d) { // parameterized method
width = w; height = h; depth = d;
}
}
class Boxdemo5{
public static void main(String args[ ]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

mybox1.setdim(10, 20, 15); // 10 is copied to w, 20 to h, 15 to d


mybox2.setdim(3, 6, 9);

vol = mybox1.volume();
System.out.println(“Volume is “ + vol);
vol=mybox2.volume();
System.out.println(“Volume is “ + vol);
}
}
Constructors
class Box {
double width; double height; double depth;
//Constructor
Box() {
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
class Boxdemo6{
public static void main(String args[ ]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

vol = mybox1.volume();
System.out.println(“Volume is “ + vol);
vol=mybox2.volume();
System.out.println(“Volume is “ + vol);
}
}
Parameterized Constructors
class Box {
double width; double height; double depth;
//Constructor
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class Boxdemo7{
public static void main(String args[ ]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;

vol = mybox1.volume();
System.out.println(“Volume is “ + vol);
vol=mybox2.volume();
System.out.println(“Volume is “ + vol);
}
}
The this keyword (25-11-2021)
• Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword.
• this can be used inside any method to refer to the current object.
• this is always a reference to an object on which the method was invoked.
• E.g., Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
• Useful when a local variable has the same name as an instance variable. The local
variable hides the instance variable.
• Used to solve any namespace collisions that might occur between instance variables
and local variables.
What is a namespace???

• Java packages are namespaces.

• They allow programmers to create small private areas which will


declare classes.

• The names of those classes will not collide with identically named
classes in different packages.
Garbage Collection(GC)
• In C++ memory released manually by use of DELETE operator.

• Java handles deallocation automatically – technique called as Garbage


Collection.

• When no reference to an object exists, that object is assumed to be no


longer needed, and memory is reclaimed.

• GC only occurs sporadically during the execution of the program.

• Different Java run-time implementations take different approaches to


GC.
The finalize( ) Method
• Sometimes an object will need to perform some action when it is destroyed.

• E.g., object is holding some non-java resource such as file handle or character
font.

• To free the object before it is destroyed, Java provides finalization., to define


specific actions that will occur when an object is to be reclaimed by Garbage
Collector.

• Add a finalize() method, to the class


The finalize( ) Method.....
• The java run time calls the method whenever it is about to recycle an object
of that class.
• General form,
protected void finalize( )
{
// finalization code here
}
• The protected keyword prevents access to finalize( ) by code defined outside
the class.
• finalize() is only called just prior to GC, and not when an object goes out-of-
scope. This means that you cannot know when –or even if – finalize() will be
executed.
Overloading Methods
• Possibility to define two or more methods within the same class share the
same name, as long as their parameter declarations are different.
• It is a Form of Polymorphism.
• Overloaded methods must differ in the type and / or number of arguments.
• Also may have different return types.
• Java executes the version of the method whose parameters match the
arguments used in the call.
Example Program
class OverloadDemo {
void test() { System.out.println(“No parameters “); }
void test(int a) { System.out.println(“a: “ + a); }
void test(int a, int b) {
S.o.println(“a and b: ” + a + “ “ + b); }
double test(double a) {S.o.println(“double a: ” + a);
return a*a; }
}
class overload {
public static void main(String args[]) {
overloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10,20);
Result = ob.test(123.25);
S.o.println(“ Result of ob.test(123.25) : “ + result);
}
}
Automatic type conversion
class OverloadDemo {
void test() { System.out.println(“No parameters “); }
void test(int a, int b){
System.out.println(“a and b: ” + a + “ “ + b); }
void test(double a){
System.out.println(“Inside test (double) :double a: ” + a); }
}
class overload {
public static void main(String args[]){
overloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10);
ob.test(10,20);
ob.test(i); // int converted to double automatically
ob.test(123.2);
}
}
Overloading Constructors
class Box { double width; double height; double depth;
//Constructor - 1
Box(double w, double h, double d) {width = w; height = h; depth = d;}
//Constructor - 2
Box() { width = -1; height = -1; depth = -1;}
// Constructor – 3
Box(double len) { width = height = depth = len;}
double volume() {
return width * height * depth; }
} //end box

class Overeloadcons{
public static void main(String args[ ]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(“Volume of mybox1 “ + vol);
vol=mybox2.volume();
System.out.println(“Volume of mybox2“ + vol);
vol = mycube.volume();
System.out.println(“Volume of mycube“ + vol);
} //end main
}// end Overloadcons
Using Object as Parameters
class Box { double width; double height; double depth;
//Pass object to Constructor
Box(Box ob) { //Pass object to constructor
width = ob.width; height = ob.height; depth = ob.depth; }
//Constructor - 2
Box(double w, double h, double d) {
width = w; height = h; depth = d; }
// Constructor – 3
Box() {
width= -1; height = -1; depth = -1;}
// Constructor – 4
Box(double len) {width = height = depth = len; } //cube created
double volume() {
return width * height * depth; } }//end Box
class Overeloadcons2{
public static void main(String args[ ]) {
Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box();
Box mycube = new Box(7); Box myclone = new Box(mybox1);
double vol;
vol = mybox1.volume();
System.out.println(“Volume of mybox1 = “ + vol);
vol=mybox2.volume();
System.out.println(“Volume of mybox2 = “ + vol);
vol = mycube.volume();
System.out.println(“Volume of mycube = “ + vol);
vol = myclone.volume();
System.out.println(“Volume of clone = “ + vol); } }
TRY THIS
Write a java program to compute area of a rectangle using parameterized constructor

class rect
{ class rectdemo
int l,b,area; {
rect(int len,int br) public static void main(String[]
{ args)
l=len; {
b=br; rect r1=new rect(12,20);
} r1.rectarea();
void rectarea()
{ }
area=l*b; }
System.out.println("area of rectangle="+ area);
}
}
A closer look at Argument Passing
• To pass an argument to a subroutine – call-by-value, call-by-reference
• Call-by-value - copies the value of an argument into the formal parameter
of the subroutine.
• Changes made to the parameter of the subroutine have no effect on the
argument.
• Call-by-reference – A reference to an argument is passed to the parameter.
• Changes made to the parameter will effect the argument used to call
the subroutine.
• In Java, passing a primitive type to a method, is passed by value.
• Objects are passed by Reference.
Objects are passed by reference
Class Test {
int a,b;
Test(int i, int j) { a = i; b = j; }
//Pass an object
Void arith(Test p) {
p.a *= 2; p.b /= 2; }
}
Class Callbyref {
p s v main(…) {
Test ob = new Test(15, 20);
s.o.println(“ ob.a and ob.b before call: “ + ob.a + “ “ + ob.b);
ob.arith(ob);
s.o.println(“ ob.a and ob.b after call: “ + ob.a + “ “ + ob.b);
}
}
Returning Objects 26-11-2021
A method can return any type of
class Retob{
data, including class types.
public static void main(String args[]){
// Returning an object.
Test ob1 = new Test(2);
class Test {
Test ob2;
int a;
Test(int i) ob2 = ob1.incrByTen( );
{a = i;} System.out.println(“ ob1.a : “ + ob1.a);
Test incrByTen( ){ System.out.println(“ ob2.a : “ + ob2.a);

Test temp = new Test (a+10); ob2 = ob2.incrByTen( );

return temp; s.o.println(“ ob2.a after second increase : + ob2.a);


}
}
}
}
Recursion
• In Java, a method can call itself. This process is called
recursion, and a method that calls itself is said to be
recursive.
• In general, recursion is the process of defining
something in terms of itself
• The key component of a recursive method is a
statement that executes a call to itself.
• Recursion is a powerful problem solving mechanism.
Recursion in Java – Example
• Java supports Recursion
// A simple example of recursion to Class recursion {
calculate factorial. public static void main(String args[ ]) {
Class Factorial{ Factorial f = new Factorial( );
int fact(int n){ System.out.println(“Factorial of 3 is “ + f.fact(3));
int result; System.out.println(“Factorial of 4 is “ + f.fact(4));
if(n == 1) return 1; System.out.println(“Factorial of 5 is “ + f.fact(5));
result = fact(n-1) * n; }
return result; }
}
}
TRY THIS
Write a recursive program countdown that takes n as a
parameter. It prints integers from n to 0 one per line &
then displays BLAST OFF

Write a recursive program add1ton that takes n as a


parameter & returns the sum 1+2+……+n
class Reccnt {
void printcnt(int count) class Recdemo{
public static void main(String[] args){
{
Reccnt r= new Reccnt();
if(count==0) r.printcnt(10);
}
System.out.println("Blast off");
else }
{
System.out.println(count);
printcnt(count-1);
}
}
}
class recadd {
int add1ton(int n){ public class Rec2 {
if (n==0)
public static void main(String[] args) {
return(n); recadd r = new recadd();
return(n+add1ton(n-1)); int s=r.add1ton(3);
} System.out.println(s);
}

} }
Introducing Access Control
• Encapsulation provides access control. Through encapsulation it is possible to control what
parts of a program can access the members of a class.
• Can prevent misuse.
• How a member can be accessed is determined by access specifier that modifies the
declaration.
• Java’s access specifier’s are public, private and protected.
• Protected - applies only when inheritance is involved.
• Public – the specified member can be accessed by any other code.
• Private - the specified member can only be accessed by other members of its class.
• main() is public – it is called by code outside the program, 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.
Example Program to differentiate between public and private (1-12-21)
Class Test { Class AccessTest {
int a; public static void main(String args[]) {
public int b; Test ob = new Test();
private int c; //These are OK, a and b may be accessed directly
ob.a = 10;
//methods to access c ob.b = 20;
void setc(int i) { // This is not OK and will cause an error
c = i; // ob.c = 100;
} // you must access c through its methods
ob.setc(100); //OK
int getc(){ //get c’s value System.out.println(“ a, b and c : “ + ob.a + “ “
return c; + ob.b + “ “ + ob.getc( ) );
} }
}
}
Understanding static
 It is possible to define a class member that will be used independently of
any object of that class.

 Normally a class member must be accessed through an object of its class,


but it is possible to create a member that can be used by itself, without
reference to a specific instance.

 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.
Understanding static
 The most common example of a static member is main( ).

 main( ) is declared as static because it must be called by the JVM when your program
begins.

 Outside the class, to use a static member, you need only specify the name of its class
followed by the dot operator.

 No object needs to be created.

 For example, if you want to assign the value 10 to a static variable called count that is
part of the Timer class, use this line:

Timer.count = 10
EXAMPLE PROGRAM
Understanding static
static is applicable for the following:
• blocks
• variables
• methods
• nested classes
• To create a static member(block,variable,method,nested class), 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.
Static variables
• When a variable is declared as static, then a single copy of variable is created
and shared among all objects at class level.

• Static variables are, essentially, global variables.

• All instances of the class share the same static variable.


class Student{ //Test class to show the values of objects
int rollno; //instance variable
String name; public class TestStaticVariable1{
static String college ="ITS";//static variable public static void main(String args[]){
//constructor
Student(int r, String n){ Student s1 = new Student(111,"Karan");
rollno = r; Student s2 = new Student(222,"Aryan");
name = n;
} //we can change the college of all objects by the si
//method to display the values ngle line of code
void display ()
{ Student.college="BBDIT";
System.out.println(rollno+" "+name+" "+college); s1.display();
}
} s2.display();
}
}
Static method
Methods declared as static have several restrictions:
• They can directly call only other static methods.
• They can directly access only static data.
• They do not have a this reference.
// Java program to demonstrate that a static member
// can be accessed before instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}
Static Blocks
• Static block is used for initializing the static variables.
• This block gets executed when the class is loaded in the memory.
• A class can have multiple Static blocks, which will execute in the same
sequence in which they have been written into the program.
Introducing Nested and Inner Classes
• In Java, you can define a class within another class. Such class is known as nested class. For
example,

class OuterClass
{
// ...
class NestedClass
{
// ...
}}

• A nested class does not exist independently of its enclosing class.


• Thus, the scope of a nested class is bounded by its outer class.
• A nested class that is declared directly within its enclosing class scope is a member of its
enclosing class.
• It is also possible to declare a nested class that is local to a block.
• There are two general types of nested classes: those that are preceded by the
static modifier and those that are not.

• non static nested class nested class is also called an inner class.

• an inner class that does not have a name is called an anonymous inner class.

• Sometimes an inner class is used to provide a set of services that is used


only by its enclosing class. Here is an example that uses an inner class to
compute various values for its enclosing class:
// outer class EXAMPLE 2
class OuterClass
{
static int outer_x = 10;
int outer_y = 20;
private int outer_private = 30;
class InnerClass
{
void display()
{ Inner class has access to all of the
System.out.println("outer_x = " + outer_x); variables and methods of its outer
System.out.println("outer_y = " + outer_y);
class and may refer to them
System.out.println("outer_private = " + outer_private);
directly
}
}
}

// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();
innerObject.display();

You might also like