Professional Documents
Culture Documents
Objects &
Inheritance
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Contents
• 4.1.1 Explain eight simple types of data. • 4.1.8 Create classes and objects.
• 4.1.2 Explain Java literals. • 4.1.9 Illustrate the use of new operator
• 4.1.3 Declare and initialize variables. and methods, constructors, method
• 4.1.4 Illustrate type conversion and overloading, ‘this’ pointer
casting features. • 4.1.10 Explain the working of static and
• 4.1.5 Illustrate use of one-dimensional final.
and two–dimensional array. • 4.1.11 Explain string classes and
• 4.1.6 Explain various types of operators. methods.
• 4.1.7 Write the syntax of selection • 4.1.12 Illustrate the use of command-
statements, iteration statements, jump, line arguments.
break, and continue statements • 4.1.13 Illustrate the Implementation of
inheritance
• 4.1.14 Illustrate the implementation of
multi level hierarchy
• 4.1.15 Illustrate the use of ‘final’ to
avoid overriding.
Hello World!
Package Statement
Import Statements
Interface Statements
Class Declarations
import java.lang.Math;
class SquareRoot
{
public static void main(String args [])
{
double x = 4;
double y;
y = Math.sqrt(x);
System.out.println("y= "+y);
}
}
Java Literals
• A literal is the source code representation of a fixed value.
• Literals in Java are a sequence of characters (digits, letters, and
other characters) that represent constant values to be stored in
variables.
• Java language specifies five major types of literals.
▫ Integer literals
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
▫ Floating literals
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal
▫ Character literals
▫ String literals
▫ Boolean literals
Numeric Literals
▫ Integer literals
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
▫ Floating literals
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal
Character and String Literals
▫ Character Literals
The ASCII character set includes 128 characters including letters, numerals,
punctuation etc.
Below table shows a set of these special characters.
▫ String Literals
The set of characters in represented as String literals in Java.
Always use "double quotes" for String literals.
Escape Meaning 'u0041' Capital letter A
\n New line '\u0030' Digit 0
\t Tab '\u0022' Double quote "
\b Backspace '\u003b' Punctuation ;
\r Carriage return '\u0020' Space
\f Formfeed '\u0009' Horizontal Tab
\\ Backslash
\' Single quotation mark "" The empty string
\" Double quotation mark "\"" A string containing
\d Octal "This is a string" A string containing 16 characters
\xd Hexadecimal "This is a " + "two- actually a string-valued constant expression,
\ud Unicode character line string" formed from two string literals
Boolean and null Literals
▫ Boolean Literals:
The values true and false are treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these
two values.
Example: boolean chosen = true;
▫ Null Literals
The final literal that we can use in Java programming is a Null literal.
We specify the Null literal in the source code as 'null'.
To reduce the number of references to an object, use null literal.
The type of the null literal is always null.
We typically assign null literals to object reference variables.
Example: s = null;
Java Data types and References
Primitive Data Types
• There are totally eight primitive data types in Java. They can be
categorized as given below:
• Integer types (Does not allow decimal places)
▫ byte
▫ short
▫ int
▫ long
• Rational Numbers(Numbers with decimal places)
▫ float
▫ double
• characters
▫ char
• conditional
▫ boolean
Data Types with Characteristics
Data Type Memory Size Default value Declaration
byte 8 bits 0 byte a=9;
short 16 bits 0 short b=89;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public class MainClass /*Type Casting - Representing the casting of incompatible types */
{
public static void main(String args[])
{
byte b;
int i = 399; double d = 424.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b+ "\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i+ "\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Java Arrays
• Java provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
• Declaring Array Variables:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
• Creating Arrays:
▫ You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
• The above statement does two things:
▫ It creates an array using new dataType[arraySize];
▫ It assigns the reference of the newly created array to the variable arrayRefVar.
• Declaring an array variable, creating an array, and assigning the reference of the array
to the variable can be combined in one statement:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Java Arrays
• Array is a data structure capable to hold data of similar data types.
• Following are the properties of arrays as accepted by the Java compiler.
▫ Arrays stores similar data types.
That is, array can hold data of same data type values.
This is one of the limitations of arrays compared to other data structures.
▫ Each value stored, in an array, is known as an element and all elements are indexed.
The first element added, by default, gets 0 index.
That is, the 5th element added gets an index number of 4.
▫ Elements can be retrieved by their index number.
▫ Array elements are stored in contiguous (continuous) memory locations.
▫ Once array is created, its size is fixed.
That is, at runtime if required, more elements cannot be added.
This is another limitation of arrays compared to other data structures.
▫ One array name can represent multiple values.
Array is the easiest way to store a large quantity of data of same data types.
▫ Arrays can be multidimensional.
▫ At the time of creation itself, array size should be declared (array initialization does not require
size).
▫ In Java, arrays are predefined objects.
With methods, the array elements can be manipulated.
▫ As Java does not support garbage values, unassigned elements are given default values; the
same values given to unassigned instance variables.
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++)
{ System.out.println(myList[i] + " "); }
Category Operators
Unary ++ -- + - ! ~ (type)
Arithmetic */%+-
Shift <<>>>>>
Comparison <<= >>= instanceof == !=
Bitwise &^|
Short-circuit && ||
Conditional ?:
Assignment = op=
The statements inside your source files are generally executed from top to bottom, in the order that they appear.
Control flow statements, however, break up the flow of execution by employing decision making, looping, and
branching, enabling your program to conditionally execute particular blocks of code.
This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for,
while, do-while), and the branching statements (break, continue, return) supported by the Java programming
language.
Java Control statements
• Java Control statements control the order of execution in a
java program, based on data values and conditional logic.
• There are three main categories of control flow statements;
▫ Selection statements:
if, if-else and switch.
▫ Loop statements:
while, do-while and for.
▫ Transfer statements:
break, continue, return, try-catch-finally and assert.
• We use control statements when we want to change the
default sequential order of execution
Selection: if statement
• The if statement executes a block of code
only if the specified expression is true.
• If the value is false, then the if block is
skipped and execution continues with the
rest of the program.
• You can either have a single statement or
a block of code within an if statement.
• Note that the conditional expression must
be a Boolean expression.
• The simple if statement has the following
syntax:
if (<conditional expression>)
<statement action>
Selection: extended if statement
The if-else statements The Nested if-else statements
It is basically extension of if statement. The Nested if-else statements are used where we want to make
series of decision making. Thus one if-else is nested within
if(boolean-expression)
{ another if-else. Therefore nested if-else give us to make a
if-code; decision within a decision already taken.
}
else
{ if(boolean-expression 1)
else-code; {
} if(boolean-expression 2)
{
Else-if Ladder Statements statement 1;
Else-if ladder is generally used when we want to take multiple }
decision. These multiple decision are in chains of if followed by else
{
else-if statements till n number. statement 2;
if(boolean-expression 1) }
{ }
statement-1; else
} {
else if(boolean-expression 2) statement 3;
{ }
statement-2;
}
else if(boolean-expression n)
{
statement-n;
}
else
{
default-statement;
}
public class IfStatementDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b < a");
}
}
public class IfElseStatementDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
{
System.out.println("a > b");
}
else
{
System.out.println("b < a");
}
}
}
Selection: switch statement
• if-else is limited to use in complex scenarios.
• This switch statement evaluates an expression and based on the result of expression
chooses a path that matches one of the list values.
• The list values are called as Cases.
• The expression value is matched against this cases, and which ever case match the
control moves to that switch.
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
default:
default-block
break;
}
public class SwitchCaseStatementDemo
{
public static void main(String[] args)
{
int a = 10, b = 20, c = 30;
int status = -1;
switch (status)
{
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Iteration: while statement
• The while statement is a looping construct control statement
that executes a block of code while a condition is true.
• You can either have a single statement or a block of code
within the while loop.
• The loop will never be executed if the testing expression
evaluates to false.
• The loop condition must be a boolean expression.
• The syntax of the while loop is
while (<loop condition>)
<statements>
Iteration: Java do-while Loop
• The Java do-while loop is used to
iterate a part of the program several
times.
• If the number of iteration is not fixed
and you must have to execute the loop
at least once, it is recommended to
use while loop.
• It is executed at least once because
condition is checked after loop body.
do
{
//code to be executed
}while(condition);
Iteration: for statement
• The Java for loop is used to iterate a part of the program
several times.
• If the number of iteration is fixed, it is recommended to use
for loop.
• There are three types of for loop in java.
▫ Simple For Loop for(initialization;condition;incr/decr){
//code to be executed
}
▫ For-each or Enhanced For Loop for(Type var:array){
//code to be executed
▫ Labeled For Loop }
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Iteration: Java Simple for Loop
• The simple for loop is
same as C/C++.
• We can initialize variable,
check condition and
increment/decrement
value.
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
Iteration: Java For-each Loop
• The for-each loop is used
to traverse array or
collection in java.
• We don't need to
increment value and use
subscript notation.
• It works on elements
basis not index.
• It returns element one by
one in the defined
variable.
Iteration: Java Labeled For Loop
• We can have name of each
for loop.
• To do so, we use label
before the for loop.
• It is useful if we have
nested for loop so that we
can break/continue specific
for loop.
• Normally, break and
continue keywords breaks/
continues the inner most for
loop only.
Write a Java program to print same character on each line and having character printed in Square shape form.
Write a Java program to print different character on each line and having character increment with each line.
Write a Java program to print same character on each line and having character increment with each line.
Write a Java program to print same character on each line and having character printed in diagonal form.
Write a Java program to print same character on each line and having character printed in Inverted V Shape form
Write a Java program to print same character on each line and having character printed in V Shape form.
Classes, fields, methods, constructors, and objects are the building blocks of
object-based Java applications.
An object-based Java application is a Java application whose design is based on
declaring classes, creating objects from them, and designing interactions between
those objects.
Java OOPs Concepts
• Object Oriented Programming is a paradigm that provides
many concepts such as inheritance, data binding,
polymorphism etc.
• Simula is considered as the first object-oriented programming
language.
• The programming paradigm where everything is represented as
an object, is known as truly object-oriented programming
language.
• Smalltalk is considered as the first truly object-oriented
programming language.
Traditional Procedural-Oriented languages
• Traditional procedural-oriented programming languages
(such as C, Fortran, Cobol and Pascal) suffer some
notable drawbacks in creating reusable software
components:
▫ The procedural-oriented programs are made up of functions.
Functions are less reusable.
It is very difficult to copy a function from one program and
reuse in another program because the function is likely to
reference the global variables and other functions.
In other words, functions are not well-encapsulated as a
self-contained reusable unit.
▫ The procedural languages are not suitable of high-level
abstraction for solving real life problems.
For example, C programs uses constructs such as if-else,
for-loop, array, method, pointer, which are low-level and
hard to abstract real problems such as a Customer
Relationship Management (CRM) system or a computer
soccer game.
• The traditional procedural-languages separate the data
structures (variables) and algorithms (functions).
Object-Oriented Programming Languages
• Object-oriented programming (OOP) languages are designed to
overcome these problems.
▫ The basic unit of OOP is a class, which encapsulates both the static
properties and dynamic operations within a "box", and specifies the public
interface for using these boxes.
▫ Since classes are well-encapsulated, it is easier to reuse these classes.
In other words, OOP combines the data structures and algorithms of a software
entity inside the same box.
OOP languages permit higher level of abstraction for solving real-life problems.
▫ The traditional procedural language (such as C and Pascal) forces you to
think in terms of the structure of the computer (e.g. memory bits and
bytes, array, decision, loop) rather than thinking in terms of the problem
you are trying to solve.
▫ The OOP languages (such as Java, C++ and C#) let you think in the
problem space, and use software objects to represent and abstract entities
of the problem space to solve the problem.
Benefits of OOP
• The object-oriented languages focus on components that the user
perceives, with objects as the basic unit.
▫ You figure out all the objects by putting all the data and
operations that describe the user's interaction with the data.
• Object-Oriented technology has many benefits:
▫ Ease in software design
as you could think in the problem space rather than the machine's bits
and bytes.
You are dealing with high-level concepts and abstractions.
Ease in design leads to more productive software development.
▫ Ease in software maintenance:
object-oriented software are easier to understand, therefore easier to
test, debug, and maintain.
▫ Reusable software:
you don't need to keep re-inventing the wheels and re-write the same
functions for different situations.
The fastest and safest way of developing a new application is to reuse
existing codes - fully tested and proven codes.
Class & Instances
• In Java, a class is a definition of objects of the same kind.
▫ In other words, a class is a blueprint, template, or prototype that defines
and describes the static attributes and dynamic behaviors common to all
objects of the same kind.
• An instance is a realization of a particular item of a class.
▫ In other words, an instance is an instantiation of a class.
▫ All the instances of a class have similar properties, as described in the
class definition.
For example, you can define a class called "Student" and create three instances
of the class "Student" for "Peter", "Paul" and "Pauline".
• The term "object" usually refers to instance.
▫ But it is often used loosely, and may refer to a class or an instance.
A Class is a 3-Compartment Box Encapsulating Data and
Operations
• A class can be visualized as a three-
compartment box, as illustrated:
▫ Name (or identity): identifies the class.
▫ Variables (or attribute, state, field): contains
the static attributes of the class.
▫ Methods (or behaviors, function, operation):
contains the dynamic behaviors of the class.
• In other words, a class encapsulates the static
attributes (data) and dynamic behaviors
(operations that operate on the data) in a
box.
CLASS - Brief Summary
• A class is a programmer-defined, abstract, self-contained,
reusable software entity that mimics a real-world thing.
• A class is a 3-compartment box containing the name,
variables and the methods.
• A class encapsulates the data structures (in variables) and
algorithms (in methods).
• The values of the variables constitute its state. The methods
constitute its behaviors.
• An instance is an instantiation (or realization) of a
particular item of a class.
Class Definition in Java
In Java, we use the keyword class to define a class.
For examples:
Class Naming Convention:
public class Circle { // class name
1. A class name shall be a noun or a noun phrase made up of
double radius; // variables
several words.
String color;
2. All the words shall be initial-capitalized
double getRadius() { ...... } // methods
(camel-case).
double getArea() { ...... }
}
3. Use a singular noun for class name.
public class SoccerPlayer { // class name
4. Choose a meaningful and self-descriptive classname.
int number; // variables
String name;
int x, y;
For examples,
void run() { ...... } // methods
SoccerPlayer,
void kickBall() { ...... }
HttpProxyServer, FileInputStream, PrintStream And SocketFactory.
}
When an instance is declared but not constructed, it holds a special value called null.
Dot (.) Operator
• The variables and methods belonging to a class are formally called member
variables and member methods.
• To reference a member variable or method, you must:
▫ First identify the instance you are interested in, and then,
▫ Use the dot operator (.) to reference the desired member variable or method.
// Suppose that the class Circle has variables radius and color,
// and methods getArea() and getRadius().
// Constructor
public Shape (String color)
{
this.color = color;
}
@Override
public String toString()
{
return "Shape of color=\"" + color + "\"";
}
// All Shape subclasses must implement a method called getArea()
abstract public double getArea();
}
public class TestShape
{
public static void main(String[] args)
{
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Shape s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
// Cannot create instance of an abstract class
Shape s3 = new Shape("green"); // Compilation Error!!
}
}
In summary, an abstract class provides a template for further development.
The purpose of an abstract class is to provide a common interface (or protocol, or contract, or understanding, or naming
convention) to all its subclasses.
Notes:
•An abstract method cannot be declared final, as final method cannot be overridden.
An abstract method, on the other hand, must be overridden in a descendant before it can be used.
•An abstract method cannot be private (which generates a compilation error).
This is because private method are not visible to the subclass and thus cannot be overridden.
The Java's interface
• Java interface is a 100% abstract superclass which define a set of methods its
subclasses must support.
• An interface contains only public abstract methods (methods with signature and
no implementation) and possibly constants (public static final variables).
• You have to use the keyword "interface" to define an interface (instead of
keyword "class" for normal classes).
• The keyword public and abstract are not needed for its abstract methods as they
are mandatory.
• Similar to an abstract superclass, an interface cannot be instantiated.
• You have to create a "subclass" that implements an interface, and provide
the actual implementation of all the abstract methods.
• Unlike a normal class, where you use the keyword "extends" to derive a
subclass.
• For interface, we use the keyword "implements" to derive a subclass.
• An interface is a contract for what the classes can do.
▫ It, however, does not specify how the classes should do it.
• An interface provides a form, a protocol, a standard, a contract, a specification, a set of rules,
an interface, for all objects that implement it.
• It is a specification and rules that any object implementing it agrees to follow.
• In Java, abstract class and interface are used to separate the public interface of a class from
its implementation so as to allow the programmer to program at the interface instead of the
various implementation.
• Interface Naming Convention:
▫ Use an adjective (typically ends with "able") consisting of one or more words.
Each word shall be initial capitalized (camel-case).
For example,
Serializable, Extenalizable, Movable, Clonable, Runnable, etc.
• Which is a better design: interface or abstract superclass?
▫ There is no clear answer.
• Use abstract superclass if there is a clear class hierarchy.
• Abstract class can contain partial implementation (such as instance
variables and methods).
• Interface cannot contain any implementation, but merely defines
the behaviors.
• As an example, Java's thread can be built using
interface Runnable or superclass Thread.
"final" Class/Variable/Method
• You can declare a class, a variable or a method to be final.
• A final class cannot be sub-classed (or extended).
• A final method cannot be overridden in the subclass.
• A final variable cannot be re-assigned a new value.
▫ A final variable of primitive type is a constant, whose value cannot be changed.
• Constant Naming Convention:
▫ a noun, or noun phrase made up of several words.
▫ All words are in uppercase separated by underscore '_'.
For examples, MIN_WIDTH, MAX_VALUE, PI, RED.
• final vs. abstract:
▫ final is opposite to abstract.
▫ A final class cannot be extended; while an abstract class must be extended and the
extended class can then be instantiated.
▫ A final method cannot be overridden; while an abstract method must be overridden
to complete its implementation.
▫ [abstract modifier is applicable to class and method only.]
Command-Line Arguments
• Java's main(String[] args) method takes an argument: String[] args, i.e.,
a String array named args.
• This is known as "command-line arguments", which corresponds to the augments
provided by the user when the java program is invoked.
• For example, a Java program calledArithmetic could be invoked with additional
command-line arguments as follows (in a "cmd" shell):
java Arithmetic 12 3456 +
• Each argument, i.e., "12", "3456" and "+", is a String.
• Java runtime packs all the arguments into a String array and passes into
the main() method as args.
• For this example, args has the following properties: