JAVA - Module 2
JAVA - Module 2
USING JAVA
Course Code : 22EEE341
MODULE II
Objects, Classes and Constructors
Contents
• Working with Objects
• Implementing Classes
• Object Construction
• Static Variables and Methods
• Constructors
• Overloading
• Visibility modifiers
• Methods and objects
• Inbuilt classes like String
• Character
• String Buffer
• this reference
• nested classes
Class Fundamentals
• In object-oriented programming technique, a program is designed using
objects and classes.
• A class
• Core of OOP and java
• Defines shape and nature of an object
• Defines a new datatype, once defined it can be used to create objects of that type.
• Thus class is template, an object is an instance of a class.
• A class in Java is a logical entity only.
• An object
• In Java is the physical as well as a logical entity.
Class Fundamentals
Class Fundamentals
• Any concept you wish to implement in a Java program must be encapsulated
within a class.
• Methods that determine how a class’ data can be used
• Simple programs done so far was to encapsulate the main method.
Class in Java
• A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Class Fundamentals
Object in Java
• An entity that has state and behavior
is known as an object.
• Identity: An object identity is a unique ID, which is not visible to the external user. 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, It is used to write.
• State:- name and color
• Behavior:- writing
Class and Object
• A class is a group of
objects which have
common properties.
• It is a user defined
template or blueprint
from which objects
are created.
• Class is a logical
entity. It can't be
physical.
General Form of a Class
• To define a class
• Specify data it contains and
• Code that operates on that data
• defines interface to its data
• determines how class’ data can be used
• A class is declared by use of the class keyword.
• Syntax to declare a class:
class <class_name>{
field;
method;
}
General Form of a Class
• A simplified general form of a class definition is
class classname {
type instance-variable1;
type instance-variable2;
type methodname1(parameter-list) {
// body of method
}
Reference Variable
Object and Class Example: main within the class
//Defining a Student class.
class Student{
int id; //defining field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through
System.out.println(s1.name);
reference variable
}
}
OUTPUT??
0
null
Object construction: using new keyword in Java
NHCE, EEE
Modify Attributes
You can also modify attribute values:
NHCE, EEE
Override existing values:
public class Main {
int x = 10;
NHCE, EEE
JAVA METHOD PARAMETERS: Argument vs
Parameter
public class Example {
public static int multiply(int a, int b) //a,b are the parameters
{
return a * b;
}
public static void main(String[] args)
{
int x = 2;
int y = 5;
// the variables x and y are arguments
int product = multiply(x, y);
System.out.println("PRODUCT IS: " + product);
}
}
NHCE, EEE
NHCE, EEE
Methods
• Method without returning value
• Method with return value
• type of data returned by a method must be compatible with the return type
• variable receiving the value returned by a method must also be compatible
with the return type
• Method that takes parameters
• Parameters allow a method to be generalized.
• can operate on a variety of data and/or be used in a number of slightly
different situations.
Return Values
• The void keyword, indicates that the method should not return a
value.
• If you want the method to return a value, you can use a primitive
data type (such as int, char, etc.) instead of void, and use the return
keyword inside the method:
NHCE, EEE
Example for Return
public class Main {
static int myMethod(int x) {
return 5 + x;
}
NHCE, EEE
This example returns the sum of a method's two parameters:
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//
printing members with a white space
}
}
1) Initialization through reference variable
• Each time you create an instance of a class, you are creating an object that contains
its own copy of each instance variable defined by the class.
• Thus, every Student object will contain its own copies of the instance variables id,
name.
• These variables can be accessed using the dot (.) operator.
• The dot operator links the name of the object with the name of an instance variable.
s1.id=101;
• The compiler assign the copy of id that is contained within the s1 object the value,
101.
• The dot operator is used to access both the instance variables and the methods
within an object.
2) Initialization through method
s1.id=101;
s1.name="Sonoo";
• The above code works, it is troubling for two reasons.
• clumsy and error prone.
• in well-designed Java programs, instance variables should be accessed only
through methods defined by their class.
2) Initialization through method
• Can there be a box with no value defined for its dimensions. The
answer is no.
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Parameterized Constructors
• To construct objects of various dimensions.
• The constructor name must be same as the •Can have any other name than keyword
class name.
•Can be invoked any no: of times
• Is invoked when ever object is created
Method Overloading
• Class having multiple methods having same name but different in
parameters, it is known as Method Overloading.
• Increases the readability of the program
• can perform only one operation, with same name of the methods
• Different ways to overload the method
• By changing number of arguments
• By changing the data type
• By changing the sequence of arguments with different data type
• In java, Method Overloading is not possible by changing the return type of
the method only- to avoid ambiguity
Method Overloading
public class Addition{
// Overloaded sum(). This sum takes two int parameters
// Driver code
public int sum(int x, int y) { return (x + y); }
public static void main(String args[])
{
// Overloaded sum(). This sum takes three int parameters
Addition s = new Addition();
public int sum(int x, int y, int z)
System.out.println(s.sum(10, 20));
{
System.out.println(s.sum(10, 20, 30));
return (x + y + z);
System.out.println(s.sum(10.5, 20.5));
}
}
}
// Overloaded sum(). This sum takes two double parameters
• All the static variables are allocated and initialized only once at the
start of the program.
• Eg: variables that are common to all objects can be made static, like
• There is only one copy of a static variable or method for the whole class.
For example, the main method is static because there should only be 1
main method.
• Static methods only have access to other static variables and static
methods.
NHCE, EEE
Non-Static Variables
• Local Variables: A variable defined within a block or method or
constructor is called local variable.
• These variables are created when the block in entered or the function
is called and destroyed after exiting from the block or when the call
returns from the function.
• The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access this variable only within that
block.
• Initialisation of Local Variable is Mandatory.
Non-Static Variables
• Instance Variables: declared in a class outside any method, constructor or
block.
• As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier then the default access specifier will be used.
• Initialisation of Instance Variable is not Mandatory. Its default value is 0
NHCE, EEE
Static variables and methods in Java
NHCE, EEE
Static variable example in Java
class VariableDemo {
static int count=0;
public void increment() { Ob1 Ob2
count++;
}
public static void main(String args[]) {
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment(); Count=0
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Static Variable can be accessed directly in a static
method
class JavaExample{
static int age;
static String name;
1.a is set to 3
2.Then the static block executes, which prints a message and then initializes b
to a * 4 or 12.
4.The three println( ) statements refer to the two static variables a and b, as
well as to the local variable x.
Static Methods
Methods declared as static have several restrictions:
• They can only call other static methods.
• Only specify the name of their class followed by the dot operator.
classname.method( )
• Here, classname is the name of the class in which the static method is
declared.
Static variables can be accessed using class name Non static variables can be accessed using instance of a class
Static variables can be accessed by static and non static methods Non static variables cannot be accessed inside a static method.
Static variables reduce the amount of memory used by a Non static variables do not reduce the amount of memory used
program. by a program
In Static variable Memory is allocated only once, at the time of In non Static variable Memory is allocated each time an instance
class loading. of the class is created.
Non Static variables Can be accessed only within the class or its
Static variables Can be accessed from any part of the program.
instance.
Static variables Exists for the entire lifetime of the program. Non Static variables Exists for the lifetime of the object.
Static variables Default value is assigned automatically. Non Static variables Default value is not assigned automatically.
Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class.
Static variable is like a global variable and is available to all Non static variable is like a local variable and they can be
methods. accessed through only instance of a class.
Visibility modifiers- Introduction to access
control
• Encapsulation links data with the code that manipulates it –
thru Class and object
• Encapsulation provides another important attribute:
access control.
• Through encapsulation, you can control
• what parts of a program can access the members of a class.
• Thus can prevent misuse.
• Eg: restricting data access only through a set of methods.
• Thus class creates a “black box”
Access Modifiers in Java
• Access modifiers in Java helps to restrict the scope of
• a class, constructor , variable , method or data member.
• Private
• Protected
• Public
Access Modifiers in Java
Access Modifiers in Java
• Public:
• specified using the keyword public.
• The public access modifier has the widest scope among all other access
modifiers.
• Classes, methods or data members which are declared as public
are accessible from every where in the program.
• There is no restriction on the scope of a public data members.
Visibility modifiers
public access modifier
• It is called by code that is outside the program—that is, by the java run-
time system.
• Default:
• When no access modifier is specified for a class , method or data member – It
is said to be having the default access modifier by default.
• Having default access modifier are accessible only within the same package
Access Modifiers in Java
//error while using class from different package
package p1;
// with default modifier
// Class Geek is having Default access modifier
package p2;
class Geek
import p1.*;
{ // This class is having default access modifier
class GeekNew
void display()
{
{ public static void main(String args[])
{
System.out.println("Hello World!");
// Accessing class Geek from package p1
} Geek obj = new Geek();
obj.display();
}
}
}
Access Modifiers in Java
• Private: package p1;
• Protected:
• specified using the keyword protected.
}
The this Keyword
• In Java, this is a reference variable that refers to the current object on
which the method or constructor is being invoked.
• It can be used to access instance variables and methods of the
current object.
The this Keyword
• Using the ‘this’ keyword to refer to current class instance variables.
• Using this() to invoke the current class constructor
• Using ‘this’ keyword to return the current class instance
• Using ‘this’ keyword as the method parameter
• Using ‘this’ keyword to invoke the current class method
• Using ‘this’ keyword as an argument in the constructor call
• to differentiate between the local and instance variables
Using ‘this’ keyword to refer current class instance variables.
Local Variable has same name as Instance Variable
void display()
class Test
{
{
//Displaying value of variables a and b
int a;
System.out.println("a = " + a + " b = " + b);
int b;
}
// Parameterized constructor
public static void main(String[] args)
Test(int a, int b)
{
{
Test object = new Test(10, 20);
this.a = a;
object.display();
this.b = b;
}
}
}
Using this() to invoke current class constructor
[default constructor calling parameterized constructor]
//Parameterized constructor
class Test Test(int a, int b)
{ {
int a; this.a = a;
int b; this.b = b;
Test() //Default constructor System.out.println("Inside parameterized constructor");
{ }
this(10, 20); public static void main(String[] args)
System.out.println("Inside default {
constructor \n"); Test object = new Test();
} }
}
Using ‘this’ keyword to invoke the current class method
class Test {
void display()
{
// calling function show()
this.show();
System.out.println("Inside display function");
}
void show()
{
System.out.println("Inside show function");
}
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}
Ways to use ‘this’ keyword in java
Using this() to invoke current class constructor[parameterized constructor calling default constructor]
• Character class generally wraps the value of all the primitive type char into an
object.
• Any object of the type Character may contain a single field whose type is
char.
Java String
• String is a sequence of characters,
• for e.g. “Hello” is a string of 5 characters.
• String is probably the most commonly used class in Java’s class library.
• is same as:
String s="javatlearner";
Java String
Two Important points about string
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//
will print Sachin because strings are immutable objects
}
}
• Output: Sachin
Immutable String in Java
As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
Immutable String in Java
• But if we explicitily assign it to the reference variable, it will refer to "Sachin
Tendulkar" object.
• For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output: Sachin Tendulkar
Note:In such case, s points to the "Sachin Tendulkar". Please notice that still sachin
object is not modified.
Why string objects are immutable in java?
• Because java uses the concept of string literal.
class StringBufferExample {
sb.append("Java");
}
StringBuffer insert() method
• The insert() method inserts the given string with this string at the given position.
class StringBufferExample2{
}
StringBuffer replace() method
• The replace() method replaces the given string from the specified
beginIndex(including) and endIndex(excluding).
class StringBufferExample3{
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
StringBuffer delete() method
• The delete() method of StringBuffer class deletes the string from the specified
beginIndex(including) to endIndex(excluding).
class StringBufferExample4{
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
Character Class
• Creating a Character object :
• You can create a Character object with the Character constructor
• For example, if you pass a primitive char into a method that expects an object, the
compiler automatically converts the char to a Character for you.
• This feature is called autoboxing or unboxing, if the conversion goes the other way.
• Example
Character ch = 'a'; // Here following primitive char 'a' is boxed into the
Character object ch.
char c = test('x'); // Here primitive 'x' is boxed for method test, return is unboxed
to char 'c‘. (autoboxing/unboxing char to Character)
Methods in Character Class
• The Character class offers a number of useful class (i.e., static) methods for
manipulating characters.
class OuterClass {
...
class NestedClass {
...
}
}
Nested classes
• Scope of a nested class is bounded by the scope of its enclosing class.
• A nested class (B) has access to the members, including private members, of the
class in which it is nested (A).
• Eg: If B is a class defined inside class A, then B can access private members of
class A.
• The enclosing class does not have access to the members of the nested class.
• A static class must access the members of its enclosing class through an object.
• it cannot refer to members of its enclosing class directly, so static nested
classes are seldom used.
• Inner class
• An inner class is a non-static nested class.
• It has access to all of the variables and methods of its outer class and may
refer to them directly.
THANK YOU