Dms 6545efdcb8a19module I Part 2 Java SPP
Dms 6545efdcb8a19module I Part 2 Java SPP
by:
Dr. Soumya Priyadarsini Panda
Sr. Assistant Professor
Dept. of CSE
Silicon Institute of Technology, Bhubaneswar
Class Fundamentals
Class defines a new data type.
type methodname1(parameter-list) {
//body of method
}
type methodname2(parameter-list){
//body of method
}
...
type methodnameN(parameter-list){
//body of method
}
}
Instance Variables
The data or variables defined within a class but outside the method are
called instance variables.
Methods
A method is like function used to expose behaviour of an object.
Each instance (object) of the class contains its own copy of these
variables.
Thus the data of one object is separate and unique from the data for
other.
Example
class Box{
double width;
double height;
double depth;
}
Every Box object will contain its own copies of the instance variables
width, height and depth of each instance variable defined by the class.
To access the instance variables and methods within an object the dot(.)
operator is needed
Example:
[Link]
[Link]
[Link]
Example-1
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box b1 = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 30;
[Link] = 2;
[Link] = 3;
[Link] = 6;
[Link] = 3;
[Link] = 2;
[Link] = 6;
[Link]();
[Link]();
}
}
Example-2: Method with return type
class Box{
double width;
double height;
double depth;
vol = [Link]();
[Link](“ Volume is “ + vol);
vol = [Link]();
[Link](“ Volume is “ + vol);
}
}
Question for Homework
Define a class Rectangle, having the data members length and width.
The class should have a method which can return the area of the
Rectangle. Create another RectangleDemo class which create an object
of the Rectangle class and test the functionalities.
Constructors
//Constructor
Box() {
width = 20;
height = 20;
depth = 20;
}
//method
double volume() {
return width *height *depth;
}
Example-1 Cont…
class BoxDemo {
public static void main(String args[]) {
Box b1 = new Box(); Output:
Box b2 = new Box(); Volume is 8000.0
double vol; Volume is 8000.0
vol = [Link]();
[Link](“ Volume is “ + vol);
vol = [Link]();
[Link](“ Volume is “ + vol);
}
}
Constructors Cont…
In the line Box b1 = new Box();
Box() constructor is called.
Default Constructor
Parameterized Constructor
Default Constructor
Example:
Box() is a default constructor in previous example
Cont…
Default constructor is used to provide the default values to the object
like 0, null etc. depending on the type.
vol = [Link]();
[Link](“ Volume is “ + vol);
vol = [Link]();
[Link](“ Volume is “ + vol);
}
}
Output:
Volume is 6000.0
Volume is 36.0
Difference between Constructor and
Method
Java Constructor Java Method
Constructor is used to initialize the Method is used to expose behaviour
state of an object. of an object.
Constructor must not have return Method must have return type.
type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default Method is not provided by compiler
constructor if you don't have any in any case.
constructor.
Constructor name must be same as Method name may or may not be
the class name. same as class name.
Example-3
Define a class Stack, which perform the basic operation of stack. Define
another driver class to demonstrate the basic operations.
class Stack
{
int arr[];
int top;
int size;
Stack(int s)
{
size=s;
top = -1;
arr=new int[size];
}
void push(int item)
{
if(top==size-1)
[Link]("Overflow");
else
{
top++;
arr[top]=item;
}
}
int pop()
{
if(top<0)
{
[Link]("Underflow");
return -1;
}
else
return arr[top--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack s1 = new Stack(5); //for a stack with size 5
for(int i=1;i<=5;i++)
[Link](i);
[Link]("Elements in stack-1:");
for(int i=0;i<5;i++)
[Link](" "+ [Link]());
}
}
Output:
Elements in stack-1: 5 4 3 2 1
//for implementing 2 stacks
class TestStack
{
public static void main(String args[])
{
Stack s1 = new Stack(5); // stack1 size=5
Stack s2 = new Stack(10); //stack2 size =10
for(int i=1;i<=5;i++)
[Link](i);
for(int i=11;i<=20;i++)
[Link](i);
[Link]("Elements in stack-1:");
for(int i=0;i<5;i++)
[Link](" "+ [Link]());
[Link]("");
[Link]("Elements in stack-2:");
for(int i=0;i<10;i++)
[Link](" "+ [Link]());
}
Output:
Elements in stack-1: 5 4 3 2 1
Elements in stack-2: 20 19 18 17 16 15 14 13 12 11
Constructor Overloading
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists.
vol = [Link]();
[Link]("Volume of box2 is " + vol);
vol = [Link]();
[Link]("Volume of box3 is " + vol);
}
}
Passing Object to Constructor
class Box
{
double width;
double height;
double depth;
…….
Box()
{
width = -1;
height = -1;
depth = -1;
}
…….
// passing object to constructor
Box(Box ob)
{
width = [Link];
height = [Link];
depth = [Link];
}
…..
…..
class OverloadCons { Output:
public static void main(String args[]) { Volume of box1 is 3000.0
Box b1 = new Box(10, 20, 15); Volume of box2 is -1.0
Volume of box3 is 343.0
Box b2 = new Box(); Volume of clone box4 is 3000.0
Box b3 = new Box(7);
Box b4 = new Box(b1); // create copy of b1 in b4
double vol;
vol = [Link]();
[Link]("Volume of box1 is " + vol);
vol = [Link]();
[Link]("Volume of box2 is " + vol);
vol = [Link]();
[Link]("Volume of box3 is " + vol);
vol = [Link]();
[Link]("Volume of clone box4 is " + vol);
}
}
Question for Homework
void disp()
{
[Link](empid+ "\t\t"+name);
}
}
For one Employee
class Test
{
public static void main(String args[])
{
Employee e1=new Employee(1,“Amit");
[Link]("EMPID: \t\t NAME:);
[Link]();
}
Output:
}
EMPID: NAME:
1 Amit
For Three Employees
class Test
{
public static void main(String args[])
{
Employee e1=new Employee(1,“Amit");
Employee e2=new Employee(2,“Sumit");
Employee e3=new Employee(3,“Rohit");
[Link]("EMPID: \t\t NAME:);
[Link]();
[Link](); Output:
[Link](); EMPID: NAME:
} 1 Amit
} 2 Sumit
3 Rohit
For large number of Employees-
Use array of Objects
class Employee{
int empid;
String name;
void disp() {
[Link](empid+ "\t\t"+name);
}
//method to read data
void getData()
{
Scanner sc=new Scanner([Link]);
[Link]("enter id");
empid=[Link]();
[Link]("enter name");
name=[Link]();
}
}
class Test{
public static void main(String args[]){
int i;
Employee e[]=new Employee[3];
for(i=0;i<3;i++){
e[i]=new Employee();
}
[Link]("enter the details");
for(i=0;i<3;i++){
e[i].getData();
}
[Link]("EMPID: \t\tNAME:);
for(i=0;i<3;i++){
e[i].disp();
}
}
}
Questions
1. Define a class Rectangle, having the data members length and width.
The class should have a method which can return the area of the
Rectangle. Include both default and parameterized constructors in
the class. Create another RectangleDemo class which create an object
of the Rectangle class and test the functionalities.
2. Define a class Student having the attribute rollNo, name, branch,
cgpa and a method to display the student details. Define default and
parameterized constructors for the above class. Read the details of 5
students using an array of Student class object. Display the student
detail who has secured the highest cgpa.
Method Overloading
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
In Java, two or more methods can have same name if they differ in
parameters (different number of parameters, different types of
parameters, or both).
Write a java program to find out the area of rectangle, square and
circle using method overloading and constructor overloading.
static Keyword
The „static‟ keyword in java is used for memory management mainly.
Static instance variable are global variables which are used to refer the
common property of all objects
e.g. company name of employees, college name of students etc.
When objects of its class are declared, no copy of the static variable is
made.
All instances of the class share the same static variable.
The static variable gets memory only once in class area at the time of
class loading.
class Student{
int rollno;
String name;
String college="Silicon";
}
If there are 1000 students in a college, all instance data members will
get memory each time when an object is created
Example-2
class Student{
int rollno;
String name;
static String college="Silicon";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
[Link](rollno + “ ” + name + “ ” + college );
}
}
Cont…
class Test{
public static void main(String args[]){
Student s1 = new Student(1,“Amit");
Student s2 = new Student (2,“Sumit");
[Link]();
[Link]();
}
}
Output:
1 Amit Silicon
2 Sumit Silicon
Example-3
static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.
class Counter{
static int count=0; //will get memory only once and retain its value
Counter(){
count++;
[Link](count);
} }
Class Test{ Output:
public static void main(String args[]) { 1
Counter c1=new Counter(); 2
Counter c2=new Counter(); 3
Counter c3=new Counter();
}
}
static Method
Any method declared as static is known as static method.
A static method can only directly access static data member and can
change the value of it.
A static method cannot call non-static method directly it can call static
methods only.
[Link]();
[Link]();
[Link](); //calling a static method
Output:
[Link](); 1 Amit Silicon
[Link](); 2 Sumit Silicon
1 Amit SIT
} 2 Sumit SIT
}
Why java main method is static?
This block gets executed when the class is loaded in the memory.
Example-1
class JavaExample
{
static int num;
static String mystr;
static
{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
[Link]("Value of num: "+num);
[Link]("Value of mystr: "+mystr);
}
} Output:
Value of num: 97
Value of mystr: Static keyword in Java
Example-2
A class can have multiple Static blocks, which will execute in the same
sequence in which they have been written into the program.
class Example2{
static int num;
static String mystr;
//Static class
static class MyNestedClass
{
//non-static method
public void disp() {
/* If you make the str variable of outer class non-static then you
will get compilation error because: a nested static class cannot access non-
static members of the outer class.
*/
[Link](str);
}
Cont…
public static void main(String args[])
{
/* To create instance of nested class we didn't need the outer
class instance but for a regular nested class you would need
to create an instance of outer class first*/
Output:
BeginnersBook
this keyword
Sometimes a method may need to refer to the object that invoked it.
„this‟ can be used inside any method to refer to the current object.
That is, „this‟ is always a reference to the object on which the method
was invoked.
You can use this anywhere a reference to an object of the current class‟
type is permitted.
Use of this Keyword
1. to refer to the current class instance variable.
2. to invoke current class constructor
3. to pass as an argument in the method
4. to pass as argument in the constructor call
5. this keyword can be used to return current class instance
Example-1:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display(){
[Link](rollno+" "+name+" "+fee);
}
}
Cont…
class Test{
public static void main(String args[])
{
Student s1=new Student(1,“Amit",4000f);
Student s2=new Student(2,“Sumit",7000f);
[Link]();
[Link](); Output:
} 0 null 0.0
} 0 null 0.0
Cont…
• It is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
• When a local variable has the same name as an instance variable, the
local variable hides the instance variable.
1. to refer to the current class instance variable
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){
[Link](rollno+" "+name+" "+fee);
}
}
Cont…
class Test{
public static void main(String args[])
{
Student s1=new Student(1,“Amit",4000f);
Student s2=new Student(2,“Sumit",7000f);
[Link]();
[Link]();
}
}
Output:
1 Amit 4000.0
2 Sumit 7000.0
Example-3:
// A redundant use of this in Box example.
class Box{
double width, height, depth;
……
Box(double w, double h, double d)
{
[Link] = w;
[Link] = h;
[Link] = d;
}
…..
}
Example-4
// Use this to resolve name-space collisions.
class Box{
double width, height, depth;
……
class A{
A(){
[Link]("Hello a");
}
A(int x){
this();
[Link](x);
}
}
class Test{
public static void main(String args[]){
A a=new A(10);
}
}
Output:
Hello a
10
3. ‘this’ to pass as an argument in the method
• The this keyword can also be passed as an argument in the method. It is
used to reuse one object in many methods.
class A{
void m(A obj){
[Link]("method is invoked");
}
void p(){
m(this);
}
}
class Test{
public static void main(String args[]){
A a = new A();
a.p();
}
}
Output:
method is invoked
Cont…
(4) this: to pass as argument in the constructor call
• The „this‟ keyword can be passed in the constructor also.
• It is useful for using one object in multiple classes.
Using private modifier we can achieve encapsulation and hide data from
the outside world.
//save [Link]
// save [Link]
package pack2;
package pack1;
import pack1.*;
public class A {
class B extends A {
protected void show() {
public static void main(String args[]){
[Link]("Hello Java");
B b1 = new B();
}
[Link]();
}
}
}
Private Yes No No No
(Class Level AS)
class cmd {
public static void main(String args[]){
[Link](“[Link] arguments:”+ [Link]);
for(int i=0;i< [Link];i++){
[Link](args[i]);
}
} // To run: java cmd 10 20 30
} Output:
No. of arguments: 3
10
20
30