UNIT 1 - Java Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

Java Programming

UNIT – I
Object Oriented Thinking
Inheritance
Object Oriented Thinking
• A way of viewing world
• Class Hierarchies
• Java buzzwords
• An Overview of Java
• Data types
• Variables and Arrays
• Operators and Expressions
• Control statements
• Introducing classes , Methods and Classes
• String handling.
A way of viewing the world
A way of viewing the world
• Agents and communities
– An object-oriented program is structured as a community of
interacting agents, called objects. Where each object provides a
service (data and methods) that is used by other members of the
community.
• Messages and Methods
– In object-oriented programming, every action is initiated by passing a
message to an agent (object), which is responsible for the action. The
receiver is the object to whom the message was sent. In response to
the message, the receiver performs some method to carry out the
request. Every message may include any additional information as
arguments.
A way of viewing the world
• Responsibilities
– In object-oriented programming, behaviors of an object described in
terms of responsibilities.
• Classes and Instances
– In object-oriented programming, all objects are instances of a class.
The method invoked by an object in response to a message is decided
by the class. All the objects of a class use the same method in
response to a similar message.
• Classes Hierarchies
– In object-oriented programming, classes can be organized into a
hierarchical inheritance structure. A child class inherits properties
from the parent class that higher in the tree.
A way of viewing the world
• Method Binding, Overriding, and Exception
– In the class hierarchy, both parent and child classes may have the
same method which implemented individually. Here, the
implementation of the parent is overridden by the child. Or a class
may provide multiple definitions to a single method to work with
different arguments (overloading).
OOPs Concepts
• The object-oriented programming paradigm has the following
core concepts.
– Encapsulation
– Inheritance
– Polymorphism
– Abstraction
OOPs Concepts
• Encapsulation
– It is the process of combining data and code into a single unit (object /
class).
– In OOP, every object is associated with its data and code.
– In programming, data is defined as variables and code is defined as
methods.
– The java programming language uses the class concept to implement
encapsulation.
OOPs Concepts
• Inheritance
– It is the process of acquiring properties and behaviors from one object
to another object or one class to another class.
– In inheritance, we derive a new class from the existing class. Here, the
new class acquires the properties and behaviors from the existing
class.
– In the inheritance concept, the class which provides properties is
called as parent class and the class which receives the properties is
called as child class.
– The parent class is also known as base class or super class. The child
class is also known as derived class or sub class.
– In the inheritance, the properties and behaviors of base class
extended to its derived class, but the base class never receive
properties or behaviors from its derived class.
OOPs Concepts
OOPs Concepts
• Polymorphism
– It is the process of defining same method with different
implementation. That means creating multiple methods with different
behaviors.
– The java uses method overloading and method overriding to
implement polymorphism.
– Method overloading - multiple methods with same name but different
parameters.
– Method overriding - multiple methods with same name and same
parameters.
OOPs Concepts
OOPs Concepts
• Abstraction
– It is hiding the internal details and showing only essential functionality.
– In the abstraction concept, we do not show the actual implementation
to the end user, instead we provide only essential things.
– For example, if we want to drive a car, we does not need to know
about the internal functionality like how wheel system works? how
brake system works? how music system works? etc.
OOPs Concepts
Java Buzzwords
• Java is the most popular object-oriented programming language. Java has
many advanced features, a list of key features is known as Java Buzzwords.
– Simple
– Secure
– Portable
– Object-oriented
– Robust
– Architecture-neutral (or) Platform Independent
– Multi-threaded
– Interpreted
– High performance
– Distributed
– Dynamic
Java Buzzwords
• Simple
– Java programming language is very simple and easy to learn,
understand, and code. Most of the syntaxes in java follow basic
programming language C and object-oriented programming concepts
are similar to C++. In a java programming language, many complicated
features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage
collector it makes java more simple.
• Secure
– Java is said to be more secure programming language because it does
not have pointers concept, java provides a feature "applet" which can
be embedded into a web application. The applet in java does not allow
access to other parts of the computer, which keeps away from harmful
programs like viruses and unauthorized access.
Java Buzzwords
• Portable
– Portability is one of the core features of java which enables the java
programs to run on any computer or operating system. For example,
an applet developed using java runs on a wide variety of CPUs,
operating systems, and browsers connected to the Internet.
• Object-oriented
– Java is said to be a pure object-oriented programming language. In
java, everything is an object. It supports all the features of the object-
oriented programming paradigm. The primitive data types java also
implemented as objects using wrapper classes, but still, it allows
primitive data types to archive high-performance.
Java Buzzwords
• Robust
– Java is more robust because the java code can be executed on a
variety of environments, java has a strong memory management
mechanism (garbage collector), java is a strictly typed language, it has
a strong set of exception handling mechanism, and many more.
• Architecture-neutral (or) Platform Independent
– Java has invented to archive "write once; run anywhere, any time,
forever". The java provides JVM (Java Virtual Machine) to archive
architectural-neutral or platform-independent. The JVM allows the
java program created using one operating system can be executed on
any other operating system.
Java Buzzwords
• Multi-threaded
– Java supports multi-threading programming, which allows us to write
programs that do multiple operations simultaneously.
• Interpreted
– Java enables the creation of cross-platform programs by compiling into
an intermediate representation called Java bytecode. The byte code is
interpreted to any machine code so that it runs on the native machine.
• High performance
– Java provides high performance with the help of features like JVM,
interpretation, and its simplicity.
Java Buzzwords
• Distributed
– Java programming language supports TCP/IP protocols which enable
the java to support the distributed environment of the Internet. Java
also supports Remote Method Invocation (RMI), this feature enables a
program to invoke methods across a network.

• Dynamic
– Java is said to be dynamic because the java byte code may be
dynamically updated on a running system and it has a dynamic
memory allocation and de-allocation (objects and garbage collector).
Overview of Java
• Java was created based on C and C++.
• Java uses C syntax and many of the object-oriented features
are taken from C++.
• History of Java
– The C language developed in 1972 by Dennis Ritchie had taken a
decade to become the most popular language.
– In the year of 1991 the Green Team was created a new Programming
language named “OAK”.
– After some time they found that there is already a programming
language with the name “OAK”.
– So, the green team had a meeting to choose a new name. They went
to a Coffee Shop which is just outside of the Gosling’s office and there
they have decided name as “JAVA”.
Overview of Java
• Execution Process of Java Program
– Create a source code (.java file).
– Compile the source code using javac command.
– Run or execute .class file uisng java command.
Java Data Types
Java Variables
• A variable is a named memory location used to store a data
value.
• A variable can be defined as a container that holds a data
value.
• Syntax
– data_type variable_name;
(or)
– data_type variable_name_1, variable_name_2,...;
(or)
– data_type variable_name = value;
(or)
– data_type variable_name_1 = value, variable_name_2 = value,...;
Java Variables
• In java programming language variables are clasiffied as
follows.
– Local variables
– Instance variables or Member variables or Global variables
– Static variables or Class variables
– Final variables
• Local variables
– The variables declared inside a method or a block are known as local
variables.
– A local variable is visible within the method in which it is declared.
– The local variable is created when execution control enters into the
method or block and destroyed after the method or block execution
completed.
Java Variables
• Instance variables or member variables or global variables
– The variables declared inside a class and outside any method,
constructor or block are known as instance variables or member
variables.
– These variables are visible to all the methods of the class.
– The changes made to these variables by method affects all the
methods in the class.
• Static variables or Class variables
– A static variable is a variable that declared using static keyword.
– The instance variables can be static variables but local variables can
not. Static variables are initialized only once, at the start of the
program execution.
– The static variable is access by using class name.
Java Variables
• Final variables
– A final variable is a variable that declared using final keyword.
– The final variable is initialized only once, and does not allow any
method to change it's value again.
– The variable created using final keyword acts as constant. All variables
like local, instance, and static variables can be final variables.
Java Arrays
• An array is a collection of similar data values with a single
name.
• An array can also be defined as, a special type of variable that
holds multiple values of the same data type at a time.
• In java, arrays are objects and they are created dynamically
using new operator.
• Every array in java is organized using index values. The index
value of an array starts with '0' and ends with ‘size-1'.
• We use the index value to access individual elements of an
array.
Java Arrays
• There are two types of arrays and they are as follows.
– One Dimensional Array
– Multi Dimensional Array
• Creating an array
– In the java programming language, an array must be created using
new operator and with a specific size.
– The size must be an integer value but not a byte, short, or long. We
use the following syntax to create an array.
• Syntax
– data_type array_name[ ] = new data_type[size];
(or)
– data_type[ ] array_name = new data_type[size];
Java Arrays
• Looping through an array
– An entire array is accessed using either simple for statement or for-
each statement.
• Syntax
– for( initialization ; condition ; updation ){
...
}

– for(dataType item : array) {


...
}
Java Arrays
• Multidimensional Array
– In Java, multidimensional arrays are arrays of arrays.
– To create a multidimensional array variable, specify each additional
index using another set of square brackets.
• Syntax
– data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
– data_type[ ][ ] array_name = new data_type[rows][columns];
(or)
– data_type array_name[ ][ ] = {{value1, value2}, {value3, value4},
{value5, value6},...};
Java Operators
Java Expressions
• An expression is a collection of operators and operands that
represents a specific value.
• Operator is a symbol that performs tasks like arithmetic
operations, logical operations, and conditional operations, etc.
• Operands are the values on which the operators perform the
task. Here operand can be a direct value or variable or
address of memory location.
• Types
– Infix Expression
– Postfix Expression
– Prefix Expression
Java Control Statements
Java Classes
• The java class is a template of an object. The class defines the
blueprint of an object. Every class in java forms a new data
type.
• Once a class got created, we can generate as many objects as
we want. Every class defines the properties and behaviors of
an object. All the objects of a class have the same properties
and behaviors that were defined in the class.
• Every class of java programming language has the following
characteristics.
– Identity - It is the name given to the class.
– State - Represents data values that are associated with an object.
– Behavior - Represents actions can be performed by an object.
Java Classes
Java Classes
• Creating a class
– we use the keyword class to create a class. A class in java contains properties
as variables and behaviors as methods.
class <ClassName>{
data members declaration;
methods defination;
}
• Creating an object
– an object is an instance of a class.
– When an object of a class is created, the class is said to be instantiated.
– All the objects that are created using a single class have the same properties
and methods.
– But the value of properties is different for every object. Following is the
syntax of class in the java.
<ClassName> <objectName> = new <ClassName>( );
Java Methods
• A method is a block of statements under a name that gets
executes only when it is called.
• Every method is used to perform a specific task. The major
advantage of methods is code re-usability (define the code
once, and use it many times).
• A method defined as a behavior of an object. That means, every
method in java must belong to a class.
• Every method in java must be declared inside a class.
• Every method declaration has the following characteristics.
– returnType - Specifies the data type of a return value.
– name - Specifies a unique name to identify it.
– parameters - The data values it may accept or recieve.
– { } - Defienes the block belongs to the method.
Java Methods
• Creating a method
– A method is created inside the class and it may be created with any
access specifier. However, specifying access specifier is optional.
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
Java Methods
• Calling a method
– A method call precedes with the object name of the class to which it
belongs and a dot operator.
– It may call directly if the method defined with the static modifier.
– Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.
<objectName>.<methodName>( actualArguments );
Java Constructor
• Constructor
– A constructor is a special method of a class that has the
same name as the class name.
– The constructor gets executes automatically on object
creation. It does not require the explicit method call.
– A constructor may have parameters and access specifiers
too.
– In java, if you do not provide any constructor the compiler
automatically creates a default constructor.
Java Constructor
• Constructor
public class Student {
Student() {
System.out.println("Object created!");
}
public static void main(String[] args) {
Student obj1 = new Student();
Student obj2 = new Student();
}
}
Java String Handling
• A string is a sequence of characters surrounded by double
quotations. In a java programming language, a string is the
object of a built-in class String.
• The string created using a character array can not be
extended. It does not allow to append more characters after
its definition, but it can be modified.
• The String class defined in the package java.lang package. The
String class implements Serializable, Comparable, and
CharSequence interfaces.
• The string created using the String class can be extended. It
allows us to add more characters after its definition, and also
it can be modified.
Java String Handling
• Creating a string object : we can use the following two ways to
create a string object.
– Using string literal
– Using String constructor

String title = “SRITW";


String name = new String(“SRITW CSE");
String Handling Methods
Inheritance
• Inheritance concept: Inheritance basics
• Member access, Constructors, Creating Multilevel hierarchy
• super uses, using final with inheritance
• Polymorphism-ad hoc polymorphism, pure polymorphism
• method overriding, abstract classes, Object class
• forms of inheritance
– Specialization
– Specification
– Construction
– Extension
– Limitation
– Combination
• benefits of inheritance, costs of inheritance.
Inheritance Basics
• In java, using the inheritance concept, we can use the existing
features of one class in another class.
• The inheritance provides a great advantage called code re-
usability. With the help of code re-usability, the commonly
used code in an application need not be written again and
again.
• In the inheritance, the child class acquires the features from
its parent class. But the parent class never acquires the
features from its child class.
Inheritance Basics
• In inheritance, we use the terms like parent class, child class,
base class, derived class, super class, and subclass.
• The Parent class is the class which provides features to
another class. The parent class is also known as Base class or
Super class.
• The Child class is the class which receives features from
another class. The child class is also known as the Derived
Class or Subclass.
Inheritance Basics
• There are five types of inheritances, and they are as follows.
– Simple Inheritance (or) Single Inheritance
– Multiple Inheritance
– Multi-Level Inheritance
– Hierarchical Inheritance
– Hybrid Inheritance
Inheritance Basics
Inheritance Basics
• The java programming language does not support multiple
inheritance type. However, it provides an alternate with the
concept of interfaces.
• Creating child class
class <ChildClassName> extends <ParentClassName>
{
...
//Implementation of child class

...
}
Java Access Modifiers
• In Java, the access specifiers (also known as
access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable,
method or data member of class and interface.
• There are four access specifiers
– default (or) no modifier
– public
– protected
– private
Java Access Modifiers
Java Constructors in Inheritance
• In the inheritance, the constructors never get
inherited to any child class.
• In java, the default constructor of a parent
class called automatically by the constructor
of its child class. That means when we create
an object of the child class, the parent class
constructor executed, followed by the child
class constructor executed.
Java Constructors in Inheritance
• If the parent class contains both default and
parameterized constructor, then only the
default constructor called automatically by the
child class constructor.
• The parameterized constructor of parent class
must be called explicitly using the super
keyword.
Java Super Keyword
• Super is a keyword used to refers to the parent class object.
• The super keyword came into existence to solve the
naming conflicts in the inheritance.
• When both parent class and child class have members with
the same name, then the super keyword is used to refer to
the parent class version.
• In java, the super keyword is used for the following
purposes.
– To refer parent class data members
– To refer parent class methods
– To call parent class constructor
Java Super Keyword
• Super to refer parent class data members
– When both parent class and child class have data members with the
same name, then the super keyword is used to refer to the parent
class data member from child class.
• super to refer parent class method
– When both parent class and child class have method with the same
name, then the super keyword is used to refer to the parent class
method from child class.
• super to call parent class constructor
– When an object of child class is created, it automatically calls the
parent class default-constructor before it's own. But, the
parameterized constructor of parent class must be called explicitly
using the super keyword inside the child class constructor.
Java Final Keyword
• The final is a keyword and it is used with the following things.
– With variable (to create constant)
– With method (to avoid method overriding)
– With class (to avoid inheritance)
• final with variables
– When a variable defined with the final keyword, it becomes a
constant, and it does not allow us to modify the value.
– The variable defined with the final keyword allows only a one-time
assignment, once a value assigned to it, never allows us to change it
again.
Java Final Keyword
• final with methods
– When a method defined with the final keyword, it does not allow it to
override.
– The final method extends to the child class, but the child class can not
override or re-define it. It must be used as it has implemented in the
parent class.
• final with class
– When a class defined with final keyword, it can not be extended by
any other class.
Java Polymorphism
• The polymorphism is the process of defining same method
with different implementation. That means creating multiple
methods with different behaviors.
• Polymorphism implemented using method overloading and
method overriding.
Java Polymorphism
• Ad hoc polymorphism
– The ad hoc polymorphism is a technique used to define the same
method with different implementations and different arguments.
– In a java programming language, ad hoc polymorphism carried out
with a method overloading concept.
– In ad hoc polymorphism the method binding happens at the time of
compilation.
– Ad hoc polymorphism is also known as compile-time polymorphism.
Every function call binded with the respective overloaded method
based on the arguments.
Java Polymorphism
• Pure polymorphism
– The pure polymorphism is a technique used to define the same
method with the same arguments but different implementations.
– In a java programming language, pure polymorphism carried out with
a method overriding concept.
– In pure polymorphism, the method binding happens at run time.
– Pure polymorphism is also known as run-time polymorphism.
– Every function call binding with the respective overridden method
based on the object reference.
Java Method Overriding
• The method overriding is the process of re-defining a method in a child
class that is already defined in the parent class.
• When both parent and child classes have the same method, then that
method is said to be the overriding method.
• The method overriding enables the child class to change the
implementation of the method which acquired from parent class
according to its requirement.
• In the case of the method overriding, the method binding happens at run
time.
• The method binding which happens at run time is known as late binding.
So, the method overriding follows late binding.
• The method overriding is also known as dynamic method dispatch or run
time polymorphism or pure polymorphism.
Java Method Overriding
• 10 Rules for method overriding
1. Static methods can not be overridden.
2. Final methods can not be overridden.
3. Private methods can not be overridden.
4. Constructor can not be overridden.
5. An abstract method must be overridden.
6. Use super keyword to invoke overridden method from child class.
7. The return type of the overriding method must be same as the
parent has it.
Java Method Overriding
• 10 Rules for method overriding
8. The access specifier of the overriding method can be changed, but
the visibility must increase but not decrease. For example, a
protected method in the parent class can be made public, but not
private, in the child class.
9. If the overridden method does not throw an exception in the parent
class, then the child class overriding method can only throw the
unchecked exception, throwing a checked exception is not allowed.
10. If the parent class overridden method does throw an exception, then
the child class overriding method can only throw the same, or
subclass exception, or it may not throw any exception.
Java Abstract Class
• An abstract class is a class that created using abstract
keyword. In other words, a class prefixed with abstract
keyword is known as an abstract class.
• An abstract class may contain abstract methods (methods
without implementation) and also non-abstract methods
(methods with implementation).
Syntax:
abstract class <ClassName>{ ... }
Java Object Class
• In java, the Object class is the super most class of any class
hierarchy.
• The Object class in the java programming language is present
inside the java.lang package.
• Every class in the java programming language is a subclass of
Object class by default.
• The Object class is useful when you want to refer to any
object whose type you don't know.
• Because it is the superclass of all other classes in java, it can
refer to any type of object.
Java Object Class Methods
Java Forms of Inheritance
• The inheritance concept used for the number of purposes in
the java programming language.
• One of the main purposes is substitutability.
• The substitutability means that when a child class acquires
properties from its parent class, the object of the parent class
may be substituted with the child class object.
• The substitutability can achieve using inheritance, whether
using extends or implements keywords.
Java Forms of Inheritance
• Different forms of inheritance in java.
– Specialization
– Specification
– Construction
– Extension
– Limitation
– Combination
Java Forms of Inheritance
• Specialization
– It is the most ideal form of inheritance. The subclass is a special case
of the parent class. It holds the principle of substitutability.
• Specification
– This is another commonly used form of inheritance. In this form of
inheritance, the parent class just specifies which methods should be
available to the child class but doesn't implement them. The java
provides concepts like abstract and interfaces to support this form of
inheritance. It holds the principle of substitutability.
• Construction
– This is another form of inheritance where the child class may change
the behavior defined by the parent class (overriding). It does not hold
the principle of substitutability.
Java Forms of Inheritance
• Extension
– This is another form of inheritance where the child class may add its
new properties. It holds the principle of substitutability.
• Limitation
– This is another form of inheritance where the subclass restricts the
inherited behavior. It does not hold the principle of substitutability.
• Combination
– This is another form of inheritance where the subclass inherits
properties from multiple parent classes. Java does not support
multiple inheritance type.
Benefits of Inheritance
• Inheritance helps in code reuse. The child class may use the code defined
in the parent class without re-writing it.
• Inheritance can save time and effort as the main code need not be written
again.
• Inheritance provides a clear model structure which is easy to understand.
• An inheritance leads to less development and maintenance costs.
• With inheritance, we will be able to override the methods of the base
class so that the meaningful implementation of the base class method can
be designed in the derived class. An inheritance leads to less development
and maintenance costs.
• In inheritance base class can decide to keep some data private so that it
cannot be altered by the derived class.
Costs of Inheritance
• Inheritance decreases the execution speed due to the
increased time and effort it takes, the program to jump
through all the levels of overloaded classes.
• Inheritance makes the two classes (base and inherited class)
get tightly coupled. This means one cannot be used
independently of each other.
• The changes made in the parent class will affect the behavior
of child class too.
• The overuse of inheritance makes the program more complex.

You might also like