week2
week2
TMA Pai Polytechnic Manipal Object Oriented Programming design with java 20CS43P
WEEK 2
Introduction to OOP: Building blocks: class, object, attributes, methods; Class and
objects in java; Variable: Types (local, instance, static); declaration, initialization;
comments; ‘Data types;
Object A Object B
Data Data
Functions Functions
Object C
Functions
Data
Fundamental idea behind object-oriented languages is to combine data and method that
operate on the data into a single unit.
The main purpose of object oriented approach is to eliminate the drawbacks of
procedure approach.
OOP treats data as critical element in the development of program and does not allow it
to flow freely around the system.
It ties data more closely to the functions that operate on it and projects it from accidental
modification from outside functions.
OOP allows us to decompose a problem into a number of entities called objects and then
builds data and functions around these entities.
The organization of data and functions in object oriented programs is shown in Figure.
The data of an object can be accessed only by the functions associated with that object.
Functions of one object can access the functions of other objects.
1. OBJECTS:
Objects are basic run time entities in an object oriented system.
It is an instance of class.
Object represents a person, a place, a bank account or any item that a program handles.
Program objects should be chosen such that they match closely with the real-world
objects.
For example if class is country then the objects can be India,China,Japan,USA etc.
A single class can create any number of objects.
Programming problem is analyzed in terms of objects and the nature of communication
between them.
CLASSES:
A class can be defined as an entity in which data(attributes) and functions(methods)
are put together.
A class concept is similar to the structure concept of C.
Classes are user defined data types and behave like the built-in types of a programming
language.
The entire set of data and code of an object can be made a user-defined data type with
the help of a class.
Objects are the variables of type class.
Once a class has been defined, we can create any number of objects belonging to that
class.
A class is thus a collection of objects of similar type.
For example, mango, apple and orange are members of the class fruit.
2. DATA ENCAPSULATION
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data Encapsulation is the most striking feature of a class. The data is not
accessible to the outside world and only those functions which are wrapped in the class can
access it. These functions provide the interface between the object’s data and the program.
This insulation of data from direct access by the program is called Data Hiding.
3. DATA ABSTRACTION
Abstraction refers to the act of representing essential features without including the
background details or explanations classes use the concept of abstraction and are defined as
a list of abstract attributes such as size, weight and cost, and functions to operate on these
attributes. Since classes use the concept of data abstraction, they are known as Abstract
Data Types (ADT).
5.INHERITANCE
Inheritance is a property by which the new classes are created using the old classes.
Old classes are called base class and new class is called derived class.
Inheritance support hierarchical structure.
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it.
The inheritance mechanism is that it allows the programmer to reuse a class that is
almost, but not exactly, what he wants, and to tailor the class in such a way that it does
not introduce any undesirable side effects into the rest of the classes.
Example: flying birds and non-flying birds classes are derived from birds class.
6. POLYMORPHISM
Polymorphism means the ability to take more than one form.
For example, an operation may exhibit different behaviour in different instances. The
behaviour depends upon the types of data used in the operation.
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface.
The process of making an operator, to exhibit different behaviours in different instances
is known as “Operator Overloading” and using a single function name to different types
of tasks is known as “Function Overloading”.
Polymorphism is extensively used in implementing inheritance.
8. MESSAGE PASSING:
An OOP consists of a set of objects that communicate with each other. The process of
programming in an object-oriented language therefore involves the following basic steps.
a. Creating classes that define objects and their behaviour.
b. Creating objects from class definitions.
c. Establishing communication among objects.
A message for an object is a request for execution of a procedure, and therefore will invoke
a function (procedure) in the receiving object that generates the desired result. Message
passing involves specifying the name of the object, the name of the function (message) and
the information to be sent.
BENEFITS OF OOP:
Q: What are the benefits of object-oriented programming?
Q: List any five advantages of OOP.
Q: List the advantages of OOPS.
Q: Drawback of OOP
The object oriented programming is complex to implement.
In object oriented programming , everything must be arranged in the form of
classes and modules.
APPLICATIONS OF OOP:
1. Real time systems.
2. Simulation and modelling.
3. Neural network and parallel programming.
4. Object oriented databases.
5. Hypertext, hypermedia and expertext.
6. Artificial Intelligence and Expert Systems.
7. Neural Networks and Parallel Programming.
8. Decision support and office automation systems.
9. CIM/CAD/CAM systems.
10. Pattern recognition
11. Image processing
Rules
1. It must start with a letter or underscore (-)
2. They must not begin with digit.
3. Space or any special characters are not allowed.
4. Uppercase & lowercase letters are distinct.
5. It can be of any length.
All Java components require names. Names used for classes, variables, and methods are
called identifiers. In Java, there are several points to remember about identifiers. They are
as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
void sleeping() {
….
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables (static variables)− Class variables are variables declared within a
class, outside any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into
classes of the Java Language.
Example
int a, b, c; // Declares three integers a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
This chapter will explain various variable types available in Java Language. There are three
kinds of variables in Java −
1. Local variables
2. Instance variables
3. Class/Static variables.
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
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.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to only this method.
public class Test {
public void pupAge()
{
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
Example: Following example uses age without initializing it, so it would give an error at
the time of compilation.
public class Test {
public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for sub-classes can be given for these variables with the use of access
modifiers.
Instance variables have default values. For numbers, the default value is 0, for Boolean
it is false, and for object references it is null. Values can be assigned during the
declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given accessibility),
they should be called using the fully qualified name. ObjectReference.VariableName.
Example
import java.io.*;
public class Employee {
Output:
name : Raj
salary :10000.0
Class/Static Variables
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 only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final, and static. Constant variables
never change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Static variables have default values. For numbers, the default value is 0; for Boolean,
it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can be assigned in special
static initializer blocks.
Static variables can be accessed by calling with the class
name ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants) are
all in upper case. If the static variables are not public and final, the naming syntax is the
same as instance and local variables.
Example
import java.io.*;
public class Employee {
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
Comments
Java Comments
1
/* text */
The compiler ignores everything from /* to */.
2
//text
The compiler ignores everything from // to the end of the line.
3 /** documentation */
This is a documentation comment and in general its called doc comment. The JDK
javadoc tool uses doc comments when preparing automatically generated documentation.
Comments are used to add notes and documentation to source code . The compiler ignores
everything marked as comment. Comments can appear anywhere in a java source file
except within character and string literals.
Java comments are of 3 types
1)Line comment: It is a C++ style single line comment. A line comment starts with two
forward slashes(//) and ends at the end of the line the slashes appears on.
Example: //C++ style single comment
2)Block comment: It is a C style comment. A block comment starts with a forward slash
and asterisk(/*) and ends with an asterisk and forward slash(*/). It is also called multiline
comment.
/* C-style block
Comments */
3)Documentation comment: These comments are processed by the javadoc program to
generate documentation from source code. javadoc is a program that takes the comments in
java source code and creates the html documentation pages. Documentation comment is
used specifically to document non-private classes, attribute and methods. It starts with a
forward slash and two asterisk(/**).It ends with one asterisk and a forward slash(*/).Every
thong between the delimiters is a comment.
/** This is a documentation */
Data Types
Q: Explain the data types of Java.
Data types specify the size & type of values that can be stored. Various data types used in
java are byte, short, int ,long, char, float ,double and Boolean.
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
There are two data types available in Java −
Primitive Data Types
Reference/Object Data Types
Short
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values unless there is
a concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
float
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f.
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f.
double
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values,
generally the default choice
Double data type should never be used for precise values such as currency
Default value is 0.0d, Example: double d1 = 123.4
boolean
Boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
Reference Datatypes
Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that
cannot be changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Scope of Variable
Java variables are classified into 3 types Instance Variable ,Class
Variable ,Local variable
instance and class variables are declared inside a class. Instance variable are
created when the object are instantiated & therefore these are associated with the
object.
Class variables are global to a class & belong to the entire set of objects that class
creates.
Local variables can also be declared inside program blocks that are defined
between an opening brace “{“ and close “}”.
The area in which the variables are accessible is called scope.
The program blocks can be nesting. One block can be defined within another
block.
Java Literals
A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation.
Literals can be assigned to any primitive type variable. For example −
byte a = 68; char a = 'A';
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well.
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these
number systems for literals. For example −
int decimal = 100; int octal = 0144; int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are −
Example
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001'; String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well.
They are −
Notation Character represented
\n Newline (0x0a)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\\ backslash
Type casting
Changing type of the data from one type to another type is called type casting.
Syntax: Datatype variable1=(type) variable2;
Note: Automatic type casting is done from lower to higher type.(eg: byte to int)
Calling method/function
Syntax: obj-name.methodName();
Example: s1.Display();
class className{
{
Variables;
Method1()
{
}
}