JAVA Unit 1
JAVA Unit 1
JAVA Unit 1
By Neha Gulati
OVERVIEW
Java Programming: Inheritance:
Introduction Super class
Data types Sub class
Access specifiers this and super operator
Operators Method overriding
Control statements Use of final
Arrays. Packages
Abstract class
Classes: Interface.
Fundamentals
Objects
Polymorphism:
Method overloading
Methods
Constructor overloading
Constructors.
INTRODUCTION
Java is an object oriented programming language that makes you do
anything you can do with any other programming language.
Java is related to C++ which is direct descendent of C. Much of its
characteristics java derive from these two languages.
Java derives its syntax from C, and its OOPs features were
influenced by C++.
Primary motivation behind java was need of platform independent
language.
Java
C++ CC
HISTORY
Java is a general purpose, object oriented programming language platform
developed by Sun Microsystems in 1991, originally called “Oak”, but
renamed “java” in 1995.
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed
frank and Mike Sheridan at Sun Microsystems.
The idea is to create a platform independent language that could be used to
produce code that would run on a variety of CPUs under differing
environments.
• It is designed for the development of software for consumer electronics
devices like TV,VCRs, toasters and such other electronic machine.
• This new language is based on C and C++ but removed features of C and C++
that were considered as problems in these languages and this makes java
reliable , simple and robust language.
• Java is not replacement of C++, They both are designed to solve different set
of problems , so can coexist for many years.
• Most striking features of java is “Platform neutral” language. Java is first
programming language that is not tied to any particular hardware, OS or
platform. Programs developed in java can be executed anywhere on any
system.
JAVA VS C++
C++ is platform dependent but java is platform independent
No More header files, Typedefs, Defines, or Preprocessor -Packages
No More Structures or Unions –Instance variables, No Enums
No More Multiple Inheritance but can be achieved using interfaces
Java does not support global variable
No More Goto Statements
No More Operator Overloading
No More Pointers
Java does not have template class as in C++
Java had replaced the destructor function with a finalize() function.
JAVA FEATURES
• Java is simple, small and familiar :
• Because java inherits the C/C++ syntax and many of OOPS features of
C++.
• Java does not use pointers, preprocessor header files, goto statement
and many more.
• It also eliminates operator overloading and multiple inheritance.
• It is modeled on C and C++ , so syntax is familiar.
• Complied and Interpreted:
• Java is two stage system that combines both compilation and
interpretation.
• Firstly java compiler translate source code into bytecode instruction,
then java interpreter converts bytecode into machine code and run java
program.
• Object Oriented:
• Java is true object oriented.
• All program code and data reside within objects and classes.
• Even the main function is inside a class.
CONTD…
Platform Independent and Portable:
Java programs can be easily moved from one computer system to
another, anywhere and anytime.
Changes in OS, processor and system resources will not force and
changes in java program. Why?
Because:
Java compiler generates bytecode not machine language which is machine
independent.
Size of primitive data types are machine independent.
Java is secure and robust:
Java program is secure by confining a java program to java execution
environment and not allowing it access to other parts of the computer.
Java programs are robust as they are build for multiplatform
environment. Moreover a program is said to be robust if it handles
memory management and exception condition.
CONTD…
• Java is distributed :
• Java is distributed because the program of java is compiled onto one
machine can be easily transferred to machine and executes them on
another machine. So java is specially designed for internet users which
uses the Remote Computers for executing the programs on local
machine after transferring the programs from remote computers or
either from internet.
• Java is multithreaded:
• Means handling multiple tasks simultaneously. This means we need not
wait for the application to finish one tasks before beginning another.
• Java is dynamic:
• Java is capable of dynamically linking in new class libraries , methods
and objects. Java can also determine the type of class through a query,
making it possible to either dynamically link or abort the program,
depending on the response.
WHY JAVA IS PLATFORM INDEPENDENT?
WORKING OF JAVA
Java solves the problem of platform-independence by using byte code.
The Java compiler does not produce native executable code for a particular
machine like a C compiler would. Instead it produces a special format
called byte code.
Java byte code is exactly the same on every platform.
This byte code fragment means the same thing on a Solaris workstation as it
does on a Macintosh.
Java programs that have been compiled into byte code still need an
interpreter to execute them on any given platform.
The interpreter reads the byte code and translates it into the native language
of the host machine on the fly.
Since the byte code is completely platform independent, only the interpreter
and a few native libraries need to be ported to get Java to run on a new
computer or operating system.
The rest of the runtime environment including the compiler and most of the
class libraries are written in Java.
All these pieces, the javac compiler, the java interpreter, the Java
programming language, and more are collectively referred to as Java.
BYTECODE
The key that solves both security and portability problems is the
Bytecode, output of java compiler which is not executable code.
It is highly optimized set of instructions designed to be executed by
the java runtime system, which is called the java Virtual
Machine(JVM). JVM is an interpreter for bytecode.
Translating a java program into bytecode makes it much easier to
run a program in a wide variety of environments because only the
JVM needs to be implemented for each platform.
Once a runtime package exists for given system, any java program
can run on it.
Although the details of JVM will differ from platform to platform ,
all understand the same java bytecode. Thus , the execution of
bytecode by the JVM is the easiest way to create truly portable
programs.
CONTD…
The fact that a java program is executed by JVM also helps to make
it secure because the JVM is in control, it contain the program and
prevent it from generating side effects outside the system.
When a program is complied to an intermediate form and the
interpreted by a virtual machine, it runs slower than it would run if
complied to executed code.
But in case of java the difference is not so great because bytecode is
highly optimized, the use of bytecode enables the JVM to execute
programs much faster that you might expect.
JAVA VIRTUAL MACHINE (JVM)
JVM (Java Virtual Machine) is an abstract machine. It is called a
virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which
Java bytecode can be executed.
It can also run those programs which are written in other languages
and compiled to Java bytecode.
CONTD…
JVMs are available for many hardware and software platforms.
JVM, JRE, and JDK are platform dependent because the
configuration of each operating system is different from each other.
However, Java is platform independent.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JAVA RUNTIME ENVIRONMENT (JRE)
JRE is an acronym for Java Runtime Environment. It is also written
as Java RTE.
The Java Runtime Environment is a set of software tools which are
used for running Java applications.
It is used to provide the runtime environment. It is the
implementation of JVM.
It physically exists.
It contains a set of libraries + other files that JVM uses at runtime.
JAVA DEVELOPMENT KIT (JDK)
JDK is an acronym for Java Development Kit. The Java
Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets.
It physically exists.
It contains JRE + development tools.
The JDK contains a private Java Virtual Machine (JVM) and a few
other resources such as an interpreter/loader (java), a compiler
(javac), an archiver (jar), a documentation generator (Javadoc), etc.
to complete the development of a Java Application.
DIFFERENCE BETWEEN JDK, JRE, AND JVM
To develop and run a java program we need the environment JDK.
Only to run a java program we need JRE environment.
So, I can say as a software developer I need to develop JAVA
application, I need JDK but on the client side, he/she needs JRE
only as it has to run the application not develop.
JVM is responsible to run java programs line by line as an
interpreter.
JAVA ARCHITECTURE
Java's architecture arises out of four distinct but interrelated
technologies:
the Java programming language
the Java class file format
the Java Application Programming Interface
the Java virtual machine
When you write and execute java program , all these technologies
are used in following way:
You write source file in java programming language.
Java compiler(javac) compile java source file into java class file.
Your program accesses system resources by calling methods in the
classes that implements java API , this is done by invoking methods in
class file that implements java API.
JVM is responsible to execute class files generated by java compiler.
Together JVM and java API form a platform for which all java
programs are executed.
JAVA PROGRAMMING ENVIRONMENT
JAVA PROGRAM RUN ON TOP OF JAVA
PLATFORM
the combination of the Java virtual machine and Java API is called
the Java Platform.
Java programs can run on many different kinds of computers because
the Java Platform can itself be implemented in software.
Java program can run anywhere the Java Platform is present.
JVM ARCHITECTURE
JVM is the heart of Java architecture and supports all three features
of java:
platform independence, security and network mobility.
EXPLANATION
Class Loader Sub-System: It performs the task in a sequential
way:
It loads a class file.
It checks the correctness of the class file. If any one has manipulated the
class file, then the class file can not be executed.
It allocates the memory for static variables.
It sets the default value of all static variable.
Method Area:
It is a logical memory component of JVM.
This logical section of memory holds the information about classes and
interfaces.
Static variables are treated as class variables, because they take memory
from method area.
CONTD…
Heap:
When object or array is created, memory is allocated to them from
heap.
JVM through the use of new operator allocates memory from the heap
for an object.
The JVM has a daemon thread known as Garbage Collector whose task
is to free those objects from heap whose reference is not alive in stack.
Java Stack:
Method codes are stored inside method area.
For execution, a method needs memory because of local variables and
the arguments it has taken.
This purpose is fulfilled by java stack.
Program Counter:
It keeps track of the sequence of the program.
PC register holds the address of the instructions to be executed next.
CONTD…
Native Method Stack:
When a java application invokes a native method, that application does
not only use java stack but also use the native method stack for the
execution of native methods.
The libraries required for the execution of native methods are available
to the JVM through Java Native Interface.
Execution Engine:
Generate and executes the java byte code.
It contains an interpreter and Just In Time compiler.
CLASSPATH:
It is only used by Java Class Loaders to load class files.
CLASSPATH environment variable is used by System or Application
ClassLoader to locate and load compile Java bytecodes stored in .class
file.
HOW TO SET PATH IN JAVA?
There are two ways to set the path in Java:
Temporary
Permanent
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
CONTD…
How to set Permanent Path of JDK in Windows?
For setting the permanent path of JDK, you need to follow these
steps:
Go to MyComputer properties -> advanced tab -> environment
variables -> new tab of user variable -> write path in variable name ->
write path of bin folder in variable value -> ok -> ok -> ok
JAVA CODE EXECUTION
Java code can be executed using notepad and command prompt.
Java code cab be executed using any IDE Eclipse, NetBeans.
GETTING STARTED WITH JAVA PROGRAMMING
A Simple Java Application
Compiling Programs
Executing Applications
ENTERING A PROGRAM
For most of the programs the name of the file that holds the source
code to a program is immaterial. However, this is not the case with
java. the first thing that you must learn about java is that name you
give to a source file is very important.
In java a source file is a compilation unit. It is a text file that
contains one or more class definitions. The java compiler requires
that a source file use the .java filename extension.
In java all code must reside inside a class. By convention, the name
of that class should match the name of the file that holds the
program. You should also make sure that the capitalization of the
filename matches the class name. the reason for this is that java is
case sensitive . At this point , the convention that filename
correspond to class names may seem arbitrary. However, this
convention makes it easier to maintain and organize your program.
CONTD…
To compile the program use javac filename. java.
The javac compiler creates a file called filename.class that contains
the byte code version of the program. As we know that java byte
code is the intermediate representation of your program that
contains instructions that JVM (Java Virtual Machine) will execute.
Thus, the output of the javac is not code that can be directly
executed.
To run the program you have to use java application launcher ,
called (JVM). For execution use: java filename
RULES FOR WRITING JAVA PROGRAM
Always start with class keyword
After type the program, save the file in the name of the class. ( ex:
test.java)
Source file name and class name should be same(even case also).
Extension must be .java
Compile the file using javac compiler
C:\>javac test.java
Running we must use java interpreter
C:\>java test
CREATING AND COMPILING PROGRAMS
Create/Modify Source Code
On command line for
compilation
javac Welcome.java
Source Code
On command line for
execution Compile Source Code
i.e. javac Welcome.java
java Welcome If compilation errors
Bytecode
Run Byteode
i.e. java Welcome
Result
BYTE
The smallest integer type is byte. This is a signed 8-bit type that has a
range from –128 to 127.
Variables of type byte are especially useful when you’re working with a
stream of data from a network or file. They are also useful when you’re
working with raw binary data that may not be directly compatible with
Java’s other built-in types.
CONTD…
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is
probably the least-used Java type, since it is defined as having its high
byte first
int
The most commonly used integer type is int. It is a signed 32-bit type
that has a range from –2,147,483,648 to 2,147,483,647. In addition to
other uses, variables of type int are commonly employed to control
loops and to index arrays.
long
long is a signed 64-bit type and is useful for those occasions where an
int type is not large enough to hold the desired value.
The range of a long is quite large. This makes it useful when big, whole
numbers are needed.
CONTD…
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision.
float
The type float specifies a single-precision value that uses 32 bits of
storage.
Single precision is faster on some processors and takes half as much
space as double precision, but will become imprecise when the values
are either very large or very small
double
Double precision, as denoted by the double keyword, uses 64 bits to
store a value.
Double precision is actually faster than single precision on some
modern processors that have been optimized for high-speed
mathematical calculations.
All math functions, such as sin( ), cos( ), and sqrt( ), return double
values.
CONTD…
Characters
In Java, the data type used to store characters is char. However, C/C++
programmers beware: char in Java is not the same as char in C or C++.
In C/C++, char is an integer type that is 8 bits wide. This is not the case
in Java.
Instead, Java uses Unicode to represent characters. Unicode defines a
fully international character set that can represent all of the characters
found in all human languages, in Java char is a 16-bit type.
Booleans
Java has a simple type, called boolean, for logical values. It can have
only one of two possible values, true or false.
DEFAULT VALUES OF DATA TYPES
WHY CHAR USES 2 BYTE IN JAVA AND
WHAT IS \U0000 ?
It is because java uses Unicode system not ASCII code system.
The \u0000 is the lowest range of Unicode system.
OUTPUT:
name : Manisha
salary :5000.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.
Default values are same as instance variables.
CONTD…
Static variables can be accessed by calling with the class
name ClassName.VariableName.
EXAMPLE TO UNDERSTAND THE TYPES OF VARIABLES IN
JAVA
SCOPE AND LIFETIME OF VARIABLES
Scope of a variable refers to in which areas or sections of a program
can the variable be accessed and lifetime of a variable refers to how
long the variable stays alive in memory.
General convention for a variable’s scope is, it is accessible only
within the block in which it is declared. A block begins with a left
curly brace { and ends with a right curly brace }.
As we know there are three types of variables:
1) instance variables
2) class variables and
3) local variables
NOTE: As you can see in the above program, line 14 generates an error as the variable y is not
visible in the outer block and therefore cannot be accessed.
TYPE CONVERSION AND CASTING
When you assign value of one data type to another, the two types
might not be compatible with each other.
If the two types are compatible, then Java will perform the
conversion automatically known as Automatic Type Conversion or
Implicit Coversion. For example, it is always possible to assign an
int value to a long variable.
However, not all types are compatible, and thus, not all type
conversions are implicitly allowed. For instance, there is no
conversion defined from double to byte.
Fortunately, it is still possible to obtain a conversion between
incompatible types. To do so, you must use a cast, which performs
an explicit conversion between incompatible types.
IMPLICIT CONVERSION OR COERCION
Implicit conversion takes place when two data types are
automatically converted. This happens when:
The two data types are compatible.
When we assign value of a smaller data type to a bigger data type.
Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Marks[i] =100;
}
EXAMPLE TO SUM ELEMENTS OF ARRAY
class SummingArrayElements
{
public static void main(String args[])
{
double total=0.0;
double []scores=new double[6];
scores[0]=12.2;
scores[1]=33.90;
scores[2]=16.00;
scores[3]=22.90;
scores[4]=11.00;
scores[5]=134.90;
for(int i=0;i<scores.length;i++)
total+=scores[i];
System.out.println(“Scores total=” + total);
}
}
THE FOREACH LOOPS
JDK 1.5 introduced a new for loop known as foreach loop or
enhanced for loop, which enables you to traverse the complete array
sequentially without using an index variable.
COPYING ARRAYS
Arrays are reference types, so by declaring a reference and
assigning it to an existing array, you are not creating two objects,
you are just creating two references that point to the same array.
Manipulation of one these objects will affect the other.
EXAMPLE-
OTHERWAYS TO MAKE COPY OF AN ARRAY
Iterating over an array
Using Clone()
Using System.arraycopy()
1)ITERATING OVER AN ARRAY
2)USING CLONE()
3)USING ARRAYCOPY()
MULTIDIMENSIONAL ARRAY
In java multidimensional arrays are actually arrays of arrays. To
declare a multidimensional array variable, specify each additional
index using another set of square brackets.
int two_array [] [] = new int [4][5]
In above declared two dimensional array, left index determines row
and right index determines column.
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Syntax:
The initialization block executes first before the loop starts. It is used to
initialize the loop variable.
The condition statement evaluates every time prior to when the statement (that
is usually be a block) executes, if the condition is true then only the statement
(that is usually a block) will execute.
The increment or decrement statement executes every time after the statement
(that is usually a block).
EXAMPLE-
THE FOR EACH LOOP
This was introduced in Java 5. This loop is basically used to traverse
the array or collection elements.
NESTED LOOPS
Java allows loops to be nested (i.e., loops within loops) like all the
other programming languages allows.
Nested loops means loops within loops. In other words, nested loops
means, loop inside loop inside loop and so on.
CONTD…
Let's look at one more example which also demonstrate the nested
loops:
JUMP STATEMENTS
Jump statements are used to unconditionally transfer the program
control to another part of the program.
class myclass
{
}
CONTD…
Variables declare within class are called instance variable because
each instance of class has its own copy of these variables.
Code to operate on these variables is contained in methods. Nothing
can written outside methods.
Together instance variable and methods are called members.
DECLARING OBJECTS
When you create a class, you are creating a new data type. You can
use this type to declare objects of that type.
However, obtaining objects of a class is a two-step process.
First, you must declare a variable of the class type. This variable
does not define an object.
Instead, it is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and
assign it to that variable.
You can do this using the new operator. The new operator
dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it. This reference is, more or less,
the address in memory of the object allocated by new.
Thus, in Java, all class objects must be dynamically allocated.
CONTD…
Creation of Object involves two steps –
Declaration
Allocation and Assigning
this statement is used to create an object we are going to break down this
statement in two separate statements –
STEP 1 : DECLARATION OF VARIABLE OF TYPE CLASS
Above Declaration will just declare a variable of class type.
Declared Variable is able to store the reference to an object of
Rectangle Type.
As we have not created any object of class Rectangle and
we haven’t assigned any reference to myrect1 , it will
be initialized with null.
STEP 2 : ALLOCATION AND ASSIGNING OBJECT TO VARIABLE
OF CLASS TYPE
In the above example, parameters (formal arguments) and instance variables are same. So, we are
using this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
2)THIS: TO INVOKE CURRENT CLASS METHOD
You may invoke the method of the current class by using the this
keyword. If you don't use the this keyword, compiler automatically
adds this keyword while invoking the method.
Let's see the example
CONTD…
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
3) 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. In other words, it is
used for constructor chaining.
Calling parameterized constructor from default constructor:
By anonymous object:
FINALIZATION
Sometimes an object will need to perform some action when it is
destroyed.
For example, if an object is holding some non-Java resource such as
a file handle or window character font, then you might want to make
sure these resources are freed before an object is destroyed.
To handle such situations, Java provides a mechanism called
finalization.
CONTD..
Just before destroying an object, Garbage Collector
calls finalize() method on the object to perform cleanup activities.
Once finalize() method completes, Garbage Collector destroys that
object.
This method is defined in Object class as:
protected void finalize(){}
Here, the keyword protected is a specifier that prevents access to
finalize( ) by code defined outside its class.
Based on our requirement, we can override finalize() method for
perform our cleanup activities like closing connection from
database.
The finalize() method called by Garbage Collector not JVM.
Although Garbage Collector is one of the module of JVM.
The finalize() method is never invoked more than once for any
given object.
WAYS FOR REQUESTING JVM TO RUN GARBAGE
COLLECTOR
Once we made object eligible for garbage collection, it may not
destroy immediately by garbage collector. Whenever JVM runs
Garbage Collector program, then only object will be destroyed. But
when JVM runs Garbage Collector, we can not expect.
We can also request JVM to run Garbage Collector. There are two
ways to do it :
Using System.gc() method : System class contain static method gc() for
requesting JVM to run Garbage Collector.
Using Runtime.getRuntime().gc() method : Runtime class allows the
application to interface with the JVM in which the application is
running. Hence by using its gc() method, we can request JVM to run
Garbage Collector.
// Java program to demonstrate requesting
// JVM to run Garbage Collector
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Test t1 = new Test();
Test t2 = new Test();
}
}
CONTD…
Note :
There is no guarantee that any one of above two methods will definitely
run Garbage Collector.
The call System.gc() is effectively equivalent to the call
Runtime.getRuntime().gc()
OVERLOADING
In Java it is possible to define two or more methods within the same
class that share the same name, as long as their parameter
declarations are different.
When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
Method overloading is one of the ways that Java implements
polymorphism.
When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
Thus, overloaded methods must differ in the type and/or number of
their parameters.
While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a
method.
CONTD…
Advantage of method overloading:
Method overloading increases the readability of the program.
•As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
•The short datatype can be promoted to int,long,float or double.
•The char datatype can be promoted to int,long,float or double and so on.
EXAMPLE OF METHOD OVERLOADING WITH
TYPEPROMOTION
EXAMPLE OF METHOD OVERLOADING WITH TYPE
PROMOTION IF MATCHING FOUND
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.
JAVA INHERITANCE EXAMPLE
TYPES OF INHERITANCE IN JAVA
On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported
through interface only.
CONTD…
When one class inherits multiple classes, it is known as multiple
inheritance.
For Example:
SINGLE INHERITANCE EXAMPLE In single inheritance sub classes
inherit the features of one super
class
MULTILEVEL INHERITANCE EXAMPLE
In multi level inheritance a
derive class will be inheriting a
base class and as well as the
derived class also act as the
base class to other class.
HIERARCHICAL INHERITANCE EXAMPLE
In hierarchical inheritance one class
serves as a superclass for more than
one sub class
Q) WHY MULTIPLE INHERITANCE IS NOT
SUPPORTED IN JAVA?
To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method
and you call it from child class object, there will be ambiguity to
call the method of A or B class.
Since compile-time errors are better than runtime errors, Java
renders compile-time error if you inherit 2 classes. So whether you
have same method or different, there will be compile time error.
EXAMPLE-
ORDER OF CONSTRUCTORS CALLING
The super keyword can also be used to invoke the parent class
constructor. Let's see a simple example:
Note: super() is added in each class constructor automatically by
compiler if there is no super() or this().
METHOD OVERRIDING
Method overriding is one of the way by which java achieve Run Time
Polymorphism. The version of a method that is executed will be determined by the
object that is used to invoke it.
If an object of a parent class is used to invoke the method, then the version in the
parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed.
In other words, it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed.
UNDERSTANDING THE PROBLEM WITHOUT METHOD
OVERRIDING
Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.
Example-
class You
{
void talk(Stranger obj)
{
sysout("Hi, my day was great!");
}
void talk(Beloved obj)
{
sysout("Hi, my day was great! You won't believe what happened today! Blah!Blah!
Blah!Blah!Blah!Blah!Blah!Blah!Blah!Blah! ");
}
}
CONTD..
Overriding: Happens in the inheritance hierarchy!
We learn a lot from our parents! We learn to cook to some extent.
The same delicacy with same ingredients is prepared by your
mother with a different taste and you with a different taste
(assuming). That is overriding, same function (cooking), same
parameters (ingredients), but different algorithms (cooking style).
Or, your learnt driving from you dad! But you both drive the same
vehicle differently! That is overriding.
JAVA ACCESS MODIFIERS WITH METHOD OVERRIDING
The access modifier for an overriding method can allow more, but
not less, access than the overridden method.
For example, a protected instance method in the super-class can be
made public, but not private, in the subclass.
Doing so, will generate compile-time error.
EXAMPLE-
FINAL METHODS CAN NOT BE OVERRIDDEN
If we don’t want a method to be overridden, we declare it as final.
Please see Using final with Inheritance .
POLYMORPHISM IN JAVA
Polymorphism in Java is a concept by which we can perform
a single action in different ways. Polymorphism is derived from 2
Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile
time polymorphism.
Runtime polymorphism or Dynamic Method Dispatch is a
process in which a call to an overridden method is resolved at
runtime rather than compile-time.
UPCASTING
If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting.
For example:
DYNAMIC METHOD DISPATCH
Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at runtime, rather than compile time.
This is how java implements run time polymorphism.
When an overridden method is called through a super class
reference, java determines which version of that method to execute
based upon the type of the object being referred to at that time.
EXAMPLE-
class A
public class Dynamic_Method {
{
void show() /**
{ * @param args
System.out.println("Inside A's method"); */
public static void main(String[] args) {
}}
// TODO Auto-generated method stub
class B extends A
{
void show() A a = new A();
{ B b = new B();
C c = new C();
System.out.println("Inside B's method");
}}
A x;
class C extends A x= a;
{ x.show();
void show() x= b;
{ b.show();
x=c;
System.out.println("Inside C's method");
c.show();
}} }
}
} }
OBJECT CLASS IN JAVA
There is one special class “Object” in java.
All other classes are subclass of “Object”.
Reference variable of type Object can refer to an object of all other classes.
The Object class provides some common behaviors to all the objects such as
object can be compared, object can be cloned, object can be notified etc.
Class “Object” defines following methods, which means that they are
available in every object.
METHODS OF OBJECT CLASS
ABSTRACTION IN JAVA
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text
and send the message. You don't know the internal processing about
the message delivery.
Abstraction lets you focus on what the object does instead of how it
does it.
Real World Example: When you log into your email, compose and
send a mail. Again there is a whole lot of background processing
involved, verifying the recipient, sending request to the email
server, sending your email. Here you are only interested in
composing and clicking on the send button. What really happens
when you click on the send button, is hidden from you.
WAYS TO ACHIEVE ABSTRACTION
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
ABSTRACT CLASSES
An abstract class is a class that is declared abstract—it may or may not
include abstract methods. Abstract classes cannot be instantiated, but
they can be subclassed.
An abstract class cannot be instantiated with new operator, such objects
are not useful because abstract class is not fully defined.
You can not declare abstract constructor or abstract static method.
An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon), like
this:
abstract return-type name(List of parameters);
abstract void show();
When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
However, if it does not, the subclass must also be declared abstract
abstract class My_Abst
{
Void show()
{//method body}
abstarct Void disp();
}
CONTD…
EXAMPLES-
Example of abstract class-
Output:
ANOTHER EXAMPLE OF ABSTRACT CLASS IN JAVA
PACKAGES
A java package is a group of similar types of classes, interfaces and
sub-packages.
Package in java can be categorized in two form, built-in package
and user-defined package.
There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-
defined packages
Advantage of Java Package
Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
Java package provides access protection.
Java package removes naming collision.
SIMPLE EXAMPLE OF JAVA PACKAGE
The package keyword is used to create a package in java.
If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence, you
need to import the subpackage as well.
SUBPACKAGE IN JAVA
Package inside the package is called the subpackage. It should be
created to categorize the package further.
class PackageInfo{
public static void main(String args[]){
Package p=Package.getPackage("java.lang");
System.out.println("package name: "+p.getName());
System.out.println("Specification Title: "+p.getSpecificationTitle());
System.out.println("Specification Vendor: "+p.getSpecificationVendor());
System.out.println("Specification Version: "+p.getSpecificationVersion());