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

TM2 Classes Objects

Uploaded by

Bipin Bhadra
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)
4 views

TM2 Classes Objects

Uploaded by

Bipin Bhadra
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/ 35

Classes and Objects

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Classes & Objects

Static Block

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2


Objectives
At the end of this module, you will be able to:
• Create classes and Objects

• Understand the importance of static block

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Classes & Objects

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


Classes
A class contains variable declarations and method definitions

Variable Variable declarations


declaratio
(variable describes the
ns
attributes)
Variable may be: instance variables or static variables or
final variables

Methods
definitions
Method definitions
(methods handle the behavior)
Methods may be: instance methods or static methods

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5


Defining a Class in java
Define an Employee class with instance variables and instance methods

class Employee{
class Employee int id;
String name;
Instance variables int salary;
• id
• name void setId(int i) {
•salary id = i;
}
Instance methods void setName(String n) {
name = n;
• setId(…) }
• setName(…) void setSalary(int s) {
• setSalary(…) salary = s;
}

void getEmployeeDetails( ) {
getEmployeeDetails() System.out.println (name + “ salary
is “ + salary);
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6
Basic information about a class
public class Account { Instance
double balance; Variable
public void deposit( double amount ){
balance += amount; Parameter
}
or argument
public double withdraw( double amount ){
int minimum_balance=5000;
local
if (balance >= (amount+minimum_balance)){
Variable
balance -= amount;
return amount;
}
else {
System.out.println(“Insufficient Balance”);
return 0.0;
} }
public double getbalance(){
return balance;
} } Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7
Basic information about a class (Contd.).
else {
System.out.println(“Insufficient Balance”);
return 0.0;
}
}
public double getbalance(){
return balance;
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Member variables
 The previous slide contains definition of a class called Accounts.

 A class contains members which can either be variables(fields) or methods(behaviors).

 A variable declared within a class(outside any method) is known as an instance variable.

 A variable declared within a method is known as local variable.

 Variables with method declarations are known as parameters or arguments.

 A class variable can also be declared as static where as a local variable cannot be static.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


Objects and References
 Once a class is defined, you can declare a variable (object reference) of type class
Student stud1;
Employee emp1;

 The new operator is used to create an object of that reference type

Employee emp = new Employee();

Object reference object

 Object references are used to store objects.


 Reference can be created for any type of classes (like concrete classes, abstract classes)
and interfaces. Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10
Objects and References (Contd.).
 The new operator,
Dynamically allocates memory for an object

Creates the object on the heap

Returns a reference to it

The reference is then stored in the variable

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


Employee class - Example
class Employee{
int id;
String name; Output:
int salary;
void setId(int no){ John salary is 12000
id = no;
}
void setName(String n){
name = n;
}
void setSalary(int s){
salary = s;
}
void getEmployeeDetails(){
System.out.println(name + " salary is "+ salary);
}
}
public class EmployeeDemo {
public static void main(String[] args) {
Employee emp1 = new Employee();
emp1.setId(101);
emp1.setName("John");
emp1.setSalary(12000);
emp1.getEmployeeDetails();
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12
Constructors
 While designing a class, the class designer can define within the class, a special method
called ‘constructor’

 Constructor is automatically invoked whenever an object of the class is created


 Rules to define a constructor
 A constructor has the same name as the class name

 A constructor should not have a return type

 A constructor can be defined with any access specifier (like private, public)

 A class can contain more than one constructor, So it can be overloaded

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


Constructor - Example
class Sample{
private int id;
Sample(){
id = 101;
System.out.println("Default constructor, with ID: "+id);
}
Sample(int no){
id = no;
System.out.println("One argument constructor,with ID: "+ id);
}
}
public class ConstDemo {
public static void main(String[] args) {
Sample s1 = new Sample(); Output:
Sample s2 = new Sample(102); Default constructor, with ID: 101
One argument constructor,with ID: 102
}
} © 2017 Wipro wipro.com confidential 14
Sensitivity: Internal & Restricted
this reference keyword
 Each class member function contains an implicit reference of its class type, named this

 this reference is created automatically by the compiler

 It contains the address of the object through which the function is invoked
 Use of this keyword
 this can be used to refer instance variables when there is a clash with local variables or
method arguments

 this can be used to call overloaded constructors from another constructor of the same
class

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15


this Reference (Contd.).
 Ex1:
void setId (int id){
this.id = id;
} argument
instance variable
 Ex2: variable
class Sample{
Sample(){
this("Java"); // calls overloaded constructor
System.out.println("Default constructor ");
}
Sample(String str){
System.out.println("One argument constructor "+ str);
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16
this Reference (Contd.).
 Use this.variableName to explicitly refer to the instance variable.
 Use variable Name to refer to the parameter.
 The this reference is implicitly used to refer to instance variables and methods.
 It CANNOT be used in a static method.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


Static Class Members
 Static class members are the members of a class that do not belong to an instance of a
class

 We can access static members directly by prefixing the members with the class name

ClassName.staticVariable

ClassName.staticMethod(...)

Static variables:

 Shared among all objects of the class

 Only one copy exists for the entire class to use

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


Static Class Members (Contd.).
 Stored within the class code, separately from instance variables that describe an
individual object

 Public static final variables are global constants


Static methods:
 Static methods can only access directly the static members and manipulate a class’s static
variables

 Static methods cannot access non-static members(instance variables or instance methods)


of the class

 Static method cant access this and super references


Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 19
Static Class Members – Example

class StaticDemo
{
private static int a = 0;
private int b;
public void set ( int i, int j)
{
a = i; b = j;
}
public void show( )
{
System.out.println("This is static a: " + a );
System.out.println( "This is non-static b: " + b );
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 20


Static Class Members – Example (Contd.).
public static void main(String args[ ])
{
StaticDemo x = new StaticDemo( );
StaticDemo y = new StaticDemo( );
x.set(1, 1);
x.show( );
y.set(2, 2); Output:
y.show( ); This is static a: 1
This is non-static b: 1
x.show( );
This is static a: 2
} This is non-static b: 2
} This is static a: 2
This is non-static b: 1

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 21


Time to Think
Why is main() method static ?

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 22


Time to Think(Contd.).
 If a java application has to be executed, there has to be a starting point. main() method is
supposed to be that starting point. But Java doesn’t allow you to execute any method
unless you create an object of the class where the method resides. Unless we execute the
code, how do we create an instance?

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 23


Quiz
 What will be the result, if we try to compile and execute the following code as

java Sample
class Sample{
int i_val;
public static void main(String[] xyz){
System.out.println("i_val is :"+this.i_val);
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 24


Quiz (Contd.).
 What will be the result, if we try to compile and execute the following code as

java Sample
class Sample{
int i_val=10;
Sample(int i_val){
this.i_val=i_val;
System.out.println("inside Sample i_val:
"+this.i_val);
}
public static void main(String[] xyz){
Sample o = new Sample();}
} Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 25
Quiz- Solutions
 Answer 1:
Error: this keyword cannot be referred inside static methods.
 Answer 2:
Error: No default constructor created.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 26


Static Block

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 27


The “static” block
 A static block is a block of code enclosed in braces, preceded by the keyword static

Ex :
static {
System.out.println(“Within static block”);
}

 The statements within the static block are executed automatically when the class is loaded
into JVM

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 28


The “static” block (Contd.).
 A class can have any number of static blocks and they can appear anywhere in the class

 They are executed in the order of their appearance in the class

 JVM combines all the static blocks in a class as single static block and executes them

 You can invoke static methods from the static block and they will be executed as and when
the static block gets executed

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 29


Example on the “static” block (Contd.).
class StaticBlockExample {
StaticBlockExample() {
System.out.println("Within constructor");
}
static {
System.out.println("Within 1st static block");
}
static void m1() {
System.out.println("Within static m1 method");
}
static {
System.out.println("Within 2nd static block");
m1();
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 30
Example on the “static” block (Contd.).
public static void main(String [] args) {
System.out.println("Within main");
StaticBlockExample x = new StaticBlockExample();
}
static {
System.out.println("Within 3rd static block");
}
Output:
}
Within 1st static block
Within 2nd static block
Within static m1 method
Within 3rd static block
Within main
Within constructor

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 31


Quiz
 What will be the result, if we try to compile and execute the following code as

java Sample
class Sample{
public static void main(String[] xyz){
System.out.println("Inside main method line1");
}
static {
System.out.println("Inside class line1");
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 32


Quiz- Solution
 Answer:
Inside class line1
Inside main method line1

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 33


Summary
In this module, we were able to:

• Create classes and Objects

• Understand the importance of static block

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 34


Thank You

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 35

You might also like