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

2BSC(Ds)&MPCS java unit-2 notes(1)

Uploaded by

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

2BSC(Ds)&MPCS java unit-2 notes(1)

Uploaded by

Leela Rallapudi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Chapter-3:

Classes and Objects


Class:
a class is a basic building block. It can be defined as template
that describes the data and behaviour associated with the
class instantiation. Instantiating is a class is to create an
object (variable) of that class that can be used to access the
member variables and methods of the class.

A class can also be called a logical template to create the


objects that share common properties and methods.
For example, an Employee class may contain all the
employee details in the form of variables and methods. If the
class is instantiated i.e. if an object of the class is created (say
e1), we can access all the methods or properties of the class.

Defining a Class in Java


Java provides a reserved keyword class to define a class. The
keyword must be followed by the class name. Inside the class,
we declare methods and variables.
class ClassName
{
// member variables
// class methods
}
Example:
Class Addition
{
Int a,b,c; //instance variables
Void sum() //method
{
A=10;
B=20;
C=a+b;
System.out.println(“addition of two numbers is: “ +c);
}
}
an object is a member of Java class. It is also known
as instance of the class. Note that objects are created at run
time. In simple words, object is a real word entity. For
example, dog, car, pen, desk, etc. Each object shares the
following two characteristics:
 Identity: Object identity is a unique ID. The value of the
ID is not visible to the external user. It is used internally
by the JVM to identify each object uniquely.
 State: The state of an object stored in variables (fields).
 Behavior: The methods shows the behavior of an object.

Example of an Object:

Let's take an example of dog. The state of dog includes, color,


hungry, gender, breed, and age. The dog behavior includes
running, barking, eating, sleeping, wagging tail, fetching, etc.

How to Create a Java Object?


In Java, we cannot execute any program without creating
an object.
There are the following three steps to create an object from a
class,

 Declaration
 Instantiation
 Initialization

Declaration: A variable declaration with a variable name with


an object type.
Instantiation: Java provides the new keyword to create an
object of the class.
Initialization: The new keyword is followed by a call to a
constructor.

To create an object by using new operator:


Using new Keyword:
Using the new keyword is the most popular way to create an
object or instance of the class. When we create an instance
of the class by using the new keyword, it allocates memory
(heap) for the newly created object and also returns
the reference of that object to that memory. The new
keyword is also used to create an array. The syntax for
creating an object is:

Syntax:
ClassName objectname= new ClassName();
Example:
Addition obj=new Addition();
Example Program:
Class Addition
{
Int a,b,c; //instance variables
Void sum() //method
{
A=10;
B=20;
C=a+b;
System.out.println(“addition of two numbers is: “ +c);
}
Class Maddition
{
Public static void main(String args[])
{
Addition obj=new Addition(); //object creation
Obj.sum();
}
}
************
Initializing The Instance Variables:
Instance Variable:
 The variables that are declared inside the class but
outside the scope of any method are called instance
variables in Java.
 The instance variable is initialized at the time of the
class loading or when an object of the class is created.
 An instance variable can be declared using different
access modifiers available in Java like default, private,
public, and protected.

Rules for Instance Variable in Java:


 The instance variables cannot be marked as static. Refer
to this Static variable in java.
 The instance variables must be declared outside the
class methods , and any kind of scope.
 The instance variables can be marked by the access
specifiers.
 Instance variables cannot be marked by the abstract
keyword(abstract keyword only used for the methods).
 Instance variables cannot be marked by
the strictf keyword.

Instance variable initialization using Object:


The example of initializing the instance variables using object
is given below:
Public class Sample
{
String name;
Int age;
{
Public Static void main(String args[])
{
Sample obj=new Sample();
Obj.name=”alex”; //instance variables initialization
using object
Obj.age=25;
}
}
*************
Access Specifiers: (or) Access modifiers:
The access specifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
By restricting the access permissions , the programmer can
protect the critical data from unintentional modification,
There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only


within the class. It cannot be accessed from outside the
class.
2. Default: The access level of a default modifier is only
within the package. It cannot be accessed from outside
the package. If you do not specify any access level, it will
be the default.
3. Protected: The access level of a protected modifier is
within the package and outside the package through
child class. If you do not make the child class, it cannot
be accessed from outside the package.
4. Public: The access level of a public modifier is
everywhere. It can be accessed from within the class,
outside the class, within the package and outside the
package.

Access within within outside package by subclass outside


Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

*************
Constructors:
Java constructors are special types of methods that are used to
initialize an object when it is created. It has the same name as
its class and is syntactically similar to a method. However,
constructors have no explicit return type.
Syntax:
Class classname
{
Classname()
{
//statements;
}
}
Rules for Creating Java Constructors
You must follow the below-given rules while creating Java
constructors:

 The name of the constructors must be the same as the class


name.
 Java constructors do not have a return type. Even do not
use void as a return type.
 There can be multiple constructors in the same class, this
concept is known as constructor overloading.
 The access modifiers can be used with the constructors,
use if you want to change the visibility/accessibility of
constructors.
 Java provides a default constructor that is invoked during
the time of object creation. If you create any type of
constructor, the default constructor (provided by Java) is
not invoked.

Types of Java Constructors


There are three different types of constructors in Java, we
have listed them as follows:
 Default Constructor
 No-Args Constructor
 Parameterized Constructor

Default Constructor:
If you do not create any constructor in the class, Java provides a
default constructor that initializes the object.
(or)
A constructor that have no parameter is known as default
constructor.
Syntax:
Class ClassName
[
ClassName()
{
Constructor body;
}
}

2.parameterized constructor:

A constructor that have parameters is known as


parameterized constructor.
Syntax:
Class ClassName
{
ClassName(parameter-list).
{
Constructor body;
}
}

***********
Chapter – 4
Methods in java
Method:
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also
known as functions.
 Methods must be declared inside the body of the class but
immediately after the declaration of instance variables.
The general form of a method declaration is :
Syntax:
returnType methodname(parameter list)
{
body;
}
A method has two parts:
1.Method header or Method prototype.
2.Method Body
Method header or prototype:
It contains method name, method parameters and method
return data type. Method prototype is written in the form:
Syntax: returntype methodname(parameter1 parameter2….)
Example: void sum(n1,n2)
Method body:
Below the method header, we should write the method body.
Method body consists of a group of statements which contains logic
to perform the task. Method body can be written in the following
format:
syntax:
{
statements;
}
example: {
double=a+b;
System.out.println(“sum of two=” +c);
}
Program:
class Method
{
int a,b,c;
void sum()
{
a=10;
b=20;
c=a+b;
System.out.println(“addition of a and b is=” +c);
}
}
class Method1
{
public static void main(String args[])
{
Method obj=new Method();
obj.sum();
}
}
output: Addition of a and b is=30

******************
Recursion:
A method calling itself is known as ‘recursive method’ and that
phenomenon is called “recursion”.
example:
//factorial with recursion
class Recursion
{
static long factorial(int num)
{
long result;
if(num==1)
return 1;
result=factorial(num-1)*num;
return result;
}
public static void main(String args[])
{
Ssytem.out.println(“factorial of 5 is:”);
System.out.println(Recursion.factorial(5));
}
}
output: Factorial of 5 is:
120
*************

Chapter - 5
Inheritance
Inheritance is a mechanism in which one class acquires all
properties and behaviours of another class with the specific
relationship.
 Inheritance is one of the key features of OOP that allows
us to create a new class from an existing class.
 The new class that is created is known as subclass (child
or derived class) and the existing class from where the
child class is derived is known as superclass (parent or
base class).
The extends keyword is used to perform inheritance in
Java.

Syntax:
Class A
{
Body of class A;
}
Class B extends A
{
Statements;
}
Types of Inheritance:
1.Single inheritance
2.multilevel inheritance
3.hierarchical inheritance
4.Multiple inheritance.

**************
The Keyword ‘super’ :
The “super” keyword is used in Java to refer to the immediate parent
class of a subclass. It provides a means to access and call the
members (methods and fields) of the parent class from within the
context of the subclass. This is particularly useful when both the
parent and child classes have members with the same names.
If we create an object to super class, we can access only the
super class members, but not the sub class members. But if we
create sub class object, all the members of both super and sub
classes are availableto it . This is the reason, we always create an
object to sub class in inheritance. Some times, the super class
members and sub class members may have same names. In that case,
by default only sub class members are accessible. In this situation we
are using “ super “ keyword in java.

Chapter:2
Introduction to oops
Object oriented programming:
Object oriented programming is an approach that provides a way of
modularizing programs by creating portioned memory area for both
data and functions that can be used as templates for creating copies
such modules on demand.
The main aim of the oop is to bind together the data and the
functions that operate on them so that no other part of the code can
access this data except that function.
Oop concepts are as follows: (or) characterstics of OOP :
 Class
 Object
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Message communication
Class:
A class is a collection of objects or blueprint of an object.
It is a model to create an object. Once a class has been defined ,
we can create any number of objects belonging to that class.
Class contains variables and methods. For example,
Mango,apple,and orange are members of the class Fruit.
Ex: Fruit Mango;

Object:
Student
Object
No

Name
Data
Marks

Total()

Result()
Methods

An object is a real world entity that has attributes, behavior and


properties. It is referred as to as instance of the class. Each
object contains data and code to manipulate the data.

Inheritance : It is the process by which objects of one class


acquire the properties of another class (or) it is the process of
creating of one class from already existing class.
For example the bird ‘robin’ is a part of the class ‘flying birds’
which is again a part of the class’ bird’.
Bird

Attributes
Feathers
Lay eggs

Flyingbir Non Flyin


Attribute
Attribus Feathers
Feathers Lay eggs
Lay eggs

Robin Swallow Penguin Kiwi

Attribute Attribute Attribute Attribute


sFeatherL Feathers Feathers Feathers
ay eggs Lay eggs Lay eggs Lay eggs

Polymorphism :
poly means ‘several’ and Morphism means ‘forms’. polymorphism means the ability
to take more than one form. A single function name can be used to perform different tasks. It is
extensively used in implementing inheritance.
Shape

Draw( )

Circle obj Box obj Traingle

Draw(cir) Draw(bo) Draw(tri)


Encapsulation : The wrapping up ( combination )of data and
method(functions) into a single unit is known as encapsulation. The data is not
accessible by outside functions . By using encapsulation we can accomplish
data hiding.

Information “in” Data and information “out”


methods or
functions

Message communication : An oop consists of set of objects that


communicate with each other.

Data abstraction : Abstraction refers to the act of representing essential


features without including the background details or explanation. That means
hide the implementation, hide functionality and visibility details from the user.

` ***************

Problems in Procedure Oriented Approach:


POP: Procedural Oriented Programming is a programming language
derived from structure programming and based on the concept of
calling procedure. The procedures are the Functions, routines, or sub
routines…. many programming languages use the procedural
programming paradigm , including BASIC , C and PASCAL.

Problems in pop:
 The code reusability freature is not present in procedural-
oriented programming. we have to rewrite the same
programming code many times.
 Procedural code is Difficult to relate with real- world objects,
this may make it difficult to design.
 we can not perform operations like encapsulation, inheritance
etc..
 Procedural programming mainly focuses on procedures or
functions .
 Less attention is given to the data.
 The data and functions are separate from each other
 The procedural programming approach does not work well for
large and complex systems.

************

chapter 1: Strings

and

chapter5: inheritance

notes already given in handwriting papers

You might also like