Vous êtes sur la page 1sur 31

JAVA

Basics
OOPs, Methods and
Constructors
Session 3

LEARN. DO. EARN


Agenda
Sl. No. Agenda Topics Sl. No. Agenda Topics
1 OOPs Concepts 10 this Reference

2 Classes and Objects in Detail 11 Encapsulation

3 Class and its Members 12 Encapsulation Example

4 Types of Variables/Data Members 13 Uses of Static Keyword

5 Understanding JVM Memory Structure 14 Static Variable with Example

6 Working with BufferedReader 15 Static Method

7 Methods 16 Static Initialization Blocks

8 Constructors 17 Static Import

9 Methods and Constructors - Difference 18 Short Assignments

3
OOPs Concepts
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.

The four fundamental OOP concepts are encapsulation, polymorphism, inheritance and
abstraction.

Encapsulation: Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
Polymorphism: When one task is performed in different ways, it is known as
polymorphism. In java, we use overloading and overriding to achieve polymorphism.
Inheritance: When one object acquires all the properties and behaviors of parent object, it
is known as inheritance. It provides code reusability.
Abstraction: Hiding internal details and showing functionality is known as abstraction.

4
OOPs Concepts (Contd.)
From the pictures below, identify each OOP concept

5
Classes and Objects in Detail
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). An example of
intangible object is banking system.

An object has three characteristics:


state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But,it is used internally by the JVM to identify each
object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white-its state. It is used to
write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance (result) of a class.

6
Class and its Members
A class in java can contain:

data member
method
constructor
block
class and interface

7
Class and its Members (Contd.)
Simple Example of Object and Class
In this example, we have created a Student class that has two data members id and
name. We are creating the object of the Student class by new keyword and printing the
objects value.

class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}}

8
Types of Variables/Data Members
Instance Variable:
A variable that is created inside the class but outside the method, is known as
instance variable.
Instance variable doesn't get memory at compile time. It gets memory at
runtime when object (instance) is created. That is why, it is known as instance
variable.
When space is allocated for an object in the heap, a slot for each instance
variable value is created.

9
Types of Variables/Data Members (Contd.)
Static/Class Variable:
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would be only one copy of each class variable per class, regardless of
how many objects are created from it.
Static variables are stored in static memory. It is rare to use static variables
other than the declared final and used as either public or private constants.
Static variables can be accessed by calling with the class name.
ClassName.VariableName.

10
Types of Variables/Data Members (Contd.)
Default values instance variables and static variables remain same:
For numbers, the default value is 0, for Booleans, it is false and for object
references, it is null.

Local Variable:
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.

11
Understanding JVM Memory Structure
The JVM divided as follows:
Heap, Stack, Code, Static
The code section contains your byte code.
The Stack section of memory contains methods,
local variables and reference variables.
The Heap section contains Objects (may also
contain reference variables).
The Static section contains Static data/methods.
The JVM has a heap that is the run time data area
from which memory for all class instances and
arrays are allocated. It is created at the JVM start-
up.

12
Understanding JVM Memory Structure (Contd.)
Heap memory for objects is reclaimed by an automatic memory management system which
is known as a garbage collector. The heap may be of a fixed size or may be expanded and
shrunk, depending on the garbage collector's strategy.
Non-heap memory is created at the JVM start-up and stores per-class structures such as
run-time constant pool, field and method data, and the code for methods and constructors as
well as interned Strings

13
Working with BufferedReader
java.io.BufferedReader, is a character stream I/O class. Character streams provide a convenient way
for input and output in terms of characters (Unicode). BufferedReader is mostly used for taking input
from the console, System.in. It takes an InputStreamReader object as an argument.
It reads text from a character-input stream, buffering characters so as to provide for the efficient
reading of characters, arrays, and lines.

Example:
import java.io.BufferedReader;
class Example{
public static void main(String args[])throws IOException//Bypassinga checked exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
} }

14
Methods
Method is collection of statements that are
grouped together to perform an operation

Syntax for declaring method:


<accessModifier> returnType nameOfMethod
(Parameter List)
{
//group of statements
//you need to have return statement only if you
want to return the value.
// In case if you dont want to return the value
have return type as void
return <returnValue>
}

15
Methods (Contd.)
Approaches of making methods:

1. Taking something, returning something


2. Taking something, returning nothing
3. Taking nothing, returning something
2. Taking nothing, returning nothing

16
Constructors
Constructor is a special method with same name as its class name that is used to initialize a
newly created object and is called just after the memory is allocated for the object. It can
be used to initialize the objects to the required or default values at the time of object
creation.
No return type for constructor. Not even void.
Constructors are implicitly called when objects are created
A constructor without input parameter is default constructor
If no user defined constructor is provided for a class, compiler initializes member variables
to its default values.
Constructor can be overloaded
Syntax for declaring constructor:
<accessModifier> nameOfClass (Parameter List)
{
//group of statements
}

17
Constructors (Contd.)

18
Methods and Constructors - Difference

METHOD CONSTRUCTOR

Use Expose the behaviour of Initialize the state of object


object

Name Any Same as ClassName

Return type Must No returnType

Calling Any where While instantiation of object

19
this Reference
Every class member gets a hidden parameter: the this reference.
this is a keyword in Java and this points to the current object.
The this keyword is the name of a reference that refers to an object itself. One common use
of the this keyword is to reference a classs hidden data fields.
Another common use of the this keyword is that it enables a constructor to invoke another
constructor of the same class.
this always holds address of an object which is invoking the member function. For example,

public class Circle {


private double radius;

public Circle(double radius) {


this.radius = radius;
} this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
} this is used to invoke another constructor

public double getArea() {


return this.radius * this.radius * Math.PI;
}
} Every instance variable belongs to an instance represented by this,
which is normally omitted

20
Encapsulation
Encapsulation means that the internal
representation of an object is generally hidden
from view outside of the object's definition.

Typically, only the object's own methods can


directly inspect or manipulate its fields.

Encapsulation ensures that data within an


object is protected; it can accessed only by its
methods

21
Encapsulation Example
public class EncapTest{ Benefits of Encapsulation
//Private Fields The fields of a class can be made read-only or write-
private String name; only.
private String idNum;
A class can have total control over what is stored in its
//Public methods getters fields.
public String getName(){
The users of a class do not know how the class stores
return name; }
its data. A class can change the data type of a field
public String getIdNum(){ and users of the class need not change any of their
return idNum; } code.
//Public methods setters
public void setName(String name){
this.name = name; }

public void setIdNum( String newId){


idNum = newId; }
}

22
Uses of Static Keyword
The static keyword is a multifaceted keyword in Java. It can be used in
following ways:

1) static variables
2) static methods
3) static blocks of code
4) static import
5) Nested classes

23
Static Variable with Example

24
Static Method
It is a method which belongs to the class and not to the object (instance)
A static method can access only static data. It cannot access non-static data
(instance variables)
A static method can call only other static methods and cannot call a non-static
method from it.
A static method can be accessed directly by the class name and doesnt need
any object
A static method cannot refer to this or super keywords in anyway

Example, the main method is a static method:


Syntax : <class-name>.<method-name>

25
Static Initialization Blocks
The static block, is a block of statement inside a Java class that will be
executed at the time of class loading very first time in JVM.
A static block helps to initialize the static data members, just like constructors
help to initialize instance members.
It is executed before the main method.

26
Static Import
Static imports are used to save your time and typing. If you hate to type same
thing again and again then you may find such imports interesting.
Lets understand this with the help of below examples:
Without static imports Using static imports

class Demo1{ import static java.lang.System.out;


public static void main(String args[]) import static java.lang.Math.*;
{ class Demo2{
double var1= Math.sqrt(5.0); public static void main(String args[])
double var2= Math.tan(30); {
System.out.println("Square of 5 is:"+ //instead of Math.sqrt need to use only sqrt
var1); double var1= sqrt(5.0);
System.out.println("Tan of 30 is:"+ //instead of Math.tan need to use only tan
var2); double var2= tan(30);
} //need not to use System in both the below statements
} out.println("Square of 5 is:"+var1);
out.println("Tan of 30 is:"+var2);
}
}

27
A Question
Can we execute a program without main() method?
Yes, we can execute code using static block .
As main () is static: Otherwise who would call main() without creating an
instance of the class
Since it is static, it is automatically invoked by the start up code.

28
Short Assignments
1. A constructor is used to...
a. Free memory
b. Initialize a newly created object
c. Import packages
d. Create a JVM for applets

2. this() is used to invoke a constructor of the same class


true
false

29
Short Assignments (Contd.)
3. The this reference is used in conjunction with . methods
a. static
b. non static

4. When may a constructor be called without specifying the arguments


a. When the default constructor is not called
b. when the name of the constructor differs from the name of the class
c. when there are no constructors for the class

30
THANK YOU
Email us at - support@acadgild.com

LEARN. DO. EARN

Vous aimerez peut-être aussi