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

Unit 2

Uploaded by

shamithashibu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Unit 2

Uploaded by

shamithashibu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT 2

I. Classes and Objects in Java


A collection of objects of similar type is called as a class. The classes are blueprints for the
objects and its type. In other words, classes are abstraction of objects and objects are the
instances of the classes.
A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class
 Interface
The syntax of the class is as follows:
class class_name
{
Instance_variables;
member_methods
}
Here, class is a keyword. The classname is the user defined name for the class type and it
should be a valid java identifier. Instance_variables are the member data of the class.
Instance variable in Java
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. They are declared as :
Data-type instance-variable;
Method in Java in Java
A method is like a function which will operate on the instance variables of the objects of the
class. The syntax of defining a method is as follows:
return_type method_name(argument list
{
statements;
}
Return_type is the type of the value expected to be returned from the method. The
method_name is the name of the method and it should be a valid Java identifier. The
arguments(optional) are the inputs to the method to be passed from the calling method.

Declaration and creation of objects accessing members


To be able to use the member data and to perform the operations over the member data, we
need to create objects of the class.

The process of creating an object of type classname is a two step process:

1. Declaring a reference of type classname.


2. Allocating memory for an object of type classname using new operator and assigning
the reference to the object to the reference.

The syntax of creating an object of the class type classname is as follows:


classname obj;
obj = new classname();
Or
classname obj = new classname();

.
We can access the members of an object with the help of dot( ) operator.

Example:
//Defining a Student class.
class Student
{
//defining fields
int id; //field or data member or instance variable
String name;
}
//creating main method inside the Student class
class Main
{
public static void main (String args[])
{
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}

Initialize the objects


There are three ways to initialize the objects
1. By reference
2. By method
3. By constructor
Initialising object through reference
Initializing an object means storing data into the object. where we are going to initialize the
object through a reference variable.
class Student
{
int id;
string name;
}
class Main
{
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
}
}
Output : 101 Sonoo
Initialising object through method
We are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method. we are displaying the state (data) of the objects by
invoking the displayInformation() method.

class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{System.out.println(rollno+" "+name);}
}
class Main{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output
111 Karan
222 Aryan

Initialization through a constructor


A constructor is a special method that is used to initialize objects. It has the same name as the
class and is invoked when an object of that class is created. Constructors can be used to
initialize the object's attributes to their default values or to set them to the values provided in
the constructor's parameters.

II. Stack Vs Heap Memory in Java


In Java, memory management is a vital process. It is managed by Java automatically. The
JVM divides the memory into two parts: stack memory and heap memory. From the
perspective of Java, both are important memory areas but both are used for different
purposes. The major difference between Stack memory and heap memory is that the stack
is used to store the order of method execution and local variables while the heap memory
stores the objects and it uses dynamic memory allocation and deallocation. In this section, we
will discuss the differences between stack and heap in detail.

Stack Memory

The stack memory is a physical space (in RAM) allocated to each thread at run time. It is
created when a thread creates. Memory management in the stack follows LIFO (Last-In-First-
Out) order because it is accessible globally. It stores the variables, references to objects, and
partial results. Memory allocated to stack lives until the function returns. If there is no space
for creating the new objects, it throws the java.lang.StackOverFlowError. The scope of the
elements is limited to their threads. The JVM creates a separate stack for each thread.

Heap Memory

It is created when the JVM starts up and used by the application as long as the application
runs. It stores objects and JRE classes. Whenever we create objects, it occupies space in the
heap memory while the reference of that object creates in the stack. It does not follow any
order like the stack. It dynamically handles the memory blocks. It means, we need not to
handle the memory manually. For managing the memory automatically, Java provides
the garbage collector that deletes the objects which are no longer being used. Memory
allocated to heap lives until any one event, either program terminated or memory free does
not occur. The elements are globally accessible in the application. It is a common memory
space shared with all the threads. If the heap space is full, it throws
the java.lang.OutOfMemoryError. The heap memory is further divided into the following
memory areas:

III. Constructors
Constructors are special member methods of a class which are used to initialise objects when
they are created.
 In Java, a constructor is a block of codes similar to the method.
 It is called when an instance of the class is created.
 At the time of calling constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is
called.
 It calls a default constructor if there is no constructor available in the class.
 Java compiler provides a default constructor by default.
Rules for creating a constructor:
 They should have the same name as the class name.
 No return type should be specified not even void.
 A Java constructor cannot be abstract, static, final, and synchronized.

Constructors Methods
A Constructor is a block of code that A Method is a collection of statements
initializes a newly created object. which returns a value upon its execution.
A Constructor can be used to initialize an A Method consists of Java code to be
object. executed.
A Constructor is invoked implicitly by the A Method is invoked by the programmer.
system.
A Constructor is invoked when a object is A Method is invoked through method calls.
created using the keyword new.
A Constructor doesn’t have a return type. A Method must have a return type.
A Constructor initializes a object that A Method does operations on an already
doesn’t exist. created object.
A Constructor’s name must be same as the A Method’s name can be anything.
name of the class.
A class can have many Constructors but A class can have many methods but must
must not have the same parameters. not have the same parameters.
A Constructor cannot be inherited by A Method can be inherited by subclasses.
subclasses.

Types of Java constructors


 Default Constructor
 Parameterized Constructor
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter. IT will be
following form:
classname()
{
//statements;
}
The statements inside the body of the constructor will provide value for the instance variable
of the class for the object being created.
The syntax of using the constructor for creating an object is as follows:
classname obj_name = new classname()
The values of the member data of the object obj_name would be the values assigned in the
body of the constructor.
Example:
class rectangle
{
int length, breadth;
rectangle ()
{
length = 5;
breadth = 6;
}
}

In the above example class rectangle, there is a constructor without arguments. The instance
variables length and breadth of the class are assigned the values 5 and 6.
The syntax for creating the objects using constructor without arguments is as follows:
rectangle r = new rectangle ();
The values of length and breadth of the object r are 5 and 6 respectively.

Parameterized Constructor (Constructor with Arguments)


Constructors with arguments will be of following form:
classname(arguments)
{
//statements
}
The method name is same as the classname and arguments are specified within the pair of
parentheses following classname.
The statements within the body of the constructor and they are responsible for providing the
values for the instance variables of the class for the objects being created from the arguments
passed.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also.
The syntax of parameterized constructor is
classname obj_ref = new classname(arguments);

Constructor Overloading in Java


 In Java, a constructor is just like a method but without return type.
 It can also be overloaded like Java methods.
 Constructor overloading in Java
 is a technique of having more than one constructor with different parameter lists.
 They are arranged in a way that each constructor performs a different task.
 They are differentiated by the compiler by the number of parameters in the list and
their
IV. Copy Constructor
A copy constructor is a special type of constructor that creates a new object by copying the
state of an existing object of the same class.
The statements within the body of the constructor form the body of the constructor and they
are responsible for providing the values for the instance variables of the class for the objects
being created from the argument object.
class rectangle
{
int length, breadth;
rectangle( rectangle r) // passing object as a parameter
{
length = r.length;
breadth = r.breadth;
}
}
class Main
{
public static void main(String args[])
{
rectangle r1 = new rectangle();
rectangle r2 = new rectangle(r1); // copying the values of object r1 to r2
}
The object r2 is created with the help of the copy constructor with r1 as its argument.

There are many ways to copy the values of one object into another in Java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
By constructor
This involves creating a constructor in the class of the object you want to copy to which takes
an instance of that class as a parameter, and then initializes its own instance variables using
the values from the parameter object.

Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another
object without the use of a constructor
V. Static Keyword

 It is used for memory management mainly.


 Apply static keyword with variables, methods, blocks and nested classes.
 The static keyword belongs to the class than an instance of the class.
Static can be explained to following:
1. Static Variable (also known as a class variable)
2. Static Method (also known as a class method)
3. Static Block
4. Nested class

1) Static variable

The number of copies created for the member data would be equal to the number of
objects of the class type created. Under some conditions, we want one copy of data
irrespective of the number of objects instantiated. Under such conditions you can
create that particular variable as static. One main advantage of declaring a variable
as static is that, It makes your program memory efficient (i.e., it saves memory).
If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects
(which is not unique for each object),
 Example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class
loading.

Don’ts

There are two main restrictions for the static method. They are:

1. The static method cannot use non static data member or call non-static method
directly.

2. this and super cannot be used in static context.

2) Static member method

 If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a
class.
 A static method can access static data member and can change the value of it.
 They cannot refer to this or super.
 Static members can be accessed by non-static member methods.
 They can also be called as class methods as they can be invoked with the class
name.

//Java Program to get the cube of a given number using the static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println(result);
}
}

// Program illustrating static member data and static member method


class Counter
{
static int n;
Counter()
{
n=0;
}
static void incr()
{
n++;
}
void display()
{
System.out.println(“n=”+n);
}
}
class StaticMembers
{
public static void main(String args[])
{
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(“Before calling incr()”);
System.out.println(“c1:”)c1.display();
System.out.println(“After calling incr() with c1”);
System.out.println(“c1:”)c1.display();
System.out.println(“c2:”)c2.display();
c2.incr();
System.out.println(“After calling incr() with c2”);
System.out.println(“c1:”)c1.display();
System.out.println(“c2:”)c2.display();
}
}
Input-Output
Before calling incr
c1: n=0
c2: n=0
After calling incr() with c1
c1: n=1
c2: n=1
After calling incr() with c2
c1: n=2
c2 n=2
3) Static Block
A set of statements enclosed within a pair of the opening brace and the closing brace is
termed as a block of statements. If a block of statements is preceded by the keyword static,
that block of statements is called as static block. A static block is used to initialise the static
members of the class.
Syntax
Class classname
{
static member data ;
static
{
//static block begins
}
}
A static block gets executed while the class enclosing it gets loaded.

VI. this keyword


 "this" can be used to refer to the current object. .
 It can be used to refer to any member data of the class within a member method.
 The member data has to be preceded by the word this and the member operator dot.
 If there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity
 Example : "this.x" refers to the instance variable x of the current object, while "x"
without "this" would refer to the method parameter.

Class Measure
{
int feet; float inches;
void set(int feet,float inches)
{
this.feet =feet;
this.inches = inches
}
void display()
{
System.out.println(this.feet+” “+this.inches);
}
}
Class Measure1
{
Measure m = new Measure();
m.set(6, 7.5f);
m.display()
}

Usage of Java this keyword


1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
this : to invoke current class method
The method of the current class can be invoked using the this keyword. If the this keyword is
not used, the compiler automatically adds it while invoking the method.

this() : to invoke current class constructor


 The this() constructor call can be used to invoke the current class constructor.
 It is used to reuse the constructor.
 it is used for constructor chaining.

Calling default constructor from parameterized constructor:


class A
{
A()
{
System.out.println("hello a");
}
A(int x)
{
this();
System.out.println(x);
}
}
class TestThis5
{
public static void main(String args[]){
A a=new A(10);
}
}
Output:
hello a
10
this: to pass as an argument in the method

this: to pass as argument in the constructor call


 can pass the this keyword in the constructor also.
 useful if we have to use one object in multiple classes.

class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data); //using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10

VII. Nested Classes


Class defined within the scope of other class is called as a nested class. If class B is defined
within the scope of class A, then , class B is called as the inner class and class A is the outer
class.
Nested classes are further classified into two types. They are :
 Non-static nested classes
 Static nested classes
Non-static nested classes
General form of non-static nested classes is as follows:
class A
{
Instance variables
Member methods
class B
{
Instance variables
Member methods
}
}
Here, members of outer class A can be accessed by the members of inner class B directly. But
members of inner class are only accessible by the members of outer class through the object
of the inner class.
Static Nested Classes
The general form of defining static nested classes is as follows:
class A
{
instance variables
member methods
static class B
{
instance variables
member methods
}
}

Class B is the static nested class for the class A. Here members of the outer class A cannot be
accessed by the members of the static nested class B directly. But, the can access the
members of A through its objects.
class OuterClass {
int x = 10;
static class InnerClass {
int y = 5;
}}
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
}}
Output
5

VIII. Final Members and Classes


Once a variable is declared as final are given values that cannot be altered at all. Generally,
the instance is made constants with the use of the keyword final. Final could be applied to
java in following places :
1. Final variable
2. Final method
3. Final class
1) Final variable :
If you make any variable as final, you cannot change the value of final variable (It will be
constant).The syntax of declaring final members are:
final int a =10;
Here, 10 is a constant value given to the variable a. It cannot be altered later.
3) Java final class
If you make any class as final, you cannot extend it. final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile Time Error

IX. Inheritance in Java

 It is a mechanism in which one object acquires all the properties and behaviors of
a parent object.
 It is an important part of OOPs (Object Oriented programming system).
 Inheritance in Java is that you can create new classes that are built upon existing
classes.
 It inherits from an existing class
 It can reuse methods and fields of the parent class.
 It can add new methods and fields in the current class also.
 Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.

Inheritance provides Method overriding (runtime polymorphism) and Code reusability.


Terms used in Inheritance
 Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
 Reusability: As the name specifes, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name

//methods and fields

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass

Exa
mple:

class Employee // Parent class


{
float salary=40000;
}
class Programmer extends Employee // sub class
{
int bonus=10000;

}
Class Main
{
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
}
}
In this example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability
Types of inheritance in java Three types of inheritance in java:
1. single,
2. multilevel
3. and hierarchical.
Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
X.Java Interface

Another way to achieve abstraction in Java, is with interfaces.


An interface is a completely "abstract class" that is used to group related methods with empty
bodies:
Like abstract classes, interfaces cannot be used to create objects
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interface methods are by default abstract and public
Interface attributes are by default public, static and final
An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an
object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one
superclass).
It can be achieved with interfaces, because the class can implement multiple interfaces.
Syntax of interface
interface Animal
{
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by
another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class.

// Example1 Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
What is Polymorphism?
 The derivation of the word Polymorphism is from two different Greek words- poly
and
 morphs.
 “Poly” means numerous, and “Morphs” means forms.
 Polymorphism means innumerable forms.
 Polymorphism, is one of the most significant features of Object-Oriented
Programming
Types of Polymorphism
You can perform Polymorphism in Java via two different methods:
1. Method Overloading
2. Method Overriding

You might also like