Fourth Module
Fourth Module
Module IV
Programming with JAVA – Overview of Java Language, Classes Objects and Methods, Method
Overloading and Inheritance, Overriding Methods, Final Variables and Methods. Interfaces,
Packages, Multithreaded programming, Managing Errors and Exceptions.
Features of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java Is Simple
Java was designed to be easy for the programmer
For Object-oriented programmers, learning Java will be even easier.
Confusing concepts from C++ are left out of Java or implemented in a cleaner manner. Eg:explicit
pointers, operator overloading etc
Java Is Object-Oriented
Java is inherently object-oriented.
Although many object-oriented languages began strictly as procedural languages, Java was designed
from the start to be object-oriented
The object model in Java is simple and easy to extend
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior
Java Is Distributed
class Mainbox
{
public static void main(String args[])
{
Box b=new Box();
float vol;
b.length=10;
b.height=20;
b.breadth=30;
vol=b.volume();
System.out.println(vol);
}
barking...
eating...
Multilevel Inheritance
you can derive a class from the base class but you can also derive a class from the derived class. This
form of inheritance is known as multilevel inheritance.
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
Hierarchical Inheritance
If more than one class is inherited from the base class, it's known as hierarchical inheritance. In
hierarchical inheritance, all features that are common in child classes are included in the base class.
class Animal
{
void eat(){System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal
{
void meow(){System.out.println("meowing...");}
}
class TestInheritance
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Error
}}
Output:
meowing...
eating...
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 same method and you call it from child class object, there will be ambiguity to call method
of A or B class.
Parameter must be different and name Both name and parameter must be same.
must be same.
Access specifier can be changed. Access specifier most not be more restrictive than
original method
Interfaces
It is similar to classes but they lack instance variables
-their methods are declared without any body(abstract methods)
- all method inside interface must be abstract methods
One class can implement any number of interfaces
- Interface provides 100% abstraction
- Also support the concept of multiple inheritance
In this example, Printable interface has only one method, its implementation is provided in the A class.
interface Printable
{
void print();
interface Printable
{
void print();
}
interface Showable
{
interface A
{
void meth1();
void meth2();
}
Packages
Packages are containers for classes
Packages manage namespaces
Namespaces allow to group entities like classes, objects and functions under a name
Classes inside a package cannot be accessed by code outside that package
Package in java can be categorized in two form, built-in package and user-defined package.
built-in package
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
import java.io.*;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
user defined package
syntax for user defined package
package pkg;
pkg - can be any name
o First statement in java source code
o If no package is specified, the class name is put into default package without any name
o Class files must be stored in the same directory of the package
Hierarchy of packages
package pkg1.pkg2.pkg3……..;
Example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Importing packages
Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads.
It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-switching between
the threads. There can be multiple processes inside the OS and one process can have multiple threads.
Multi-Thread Programming
A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread
A thread is an independent path of execution within a program.
Every thread in Java is created and controlled by the java.lang.Thread class.
Note: - Most of the programs are single threaded
Thread priorities
Java assigns to each thread a priority
Thread priorities are integers that specify the relative priority of one thread to another.
A thread’s priority is used to decide when to switch from one running thread to the next. This is called a
context switch
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the
thread shedular picks up another thread and so on.
Naming Thread
The Thread class provides methods to change and get the name of a thread. By default, each thread has a
name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName()
method. The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Example of naming a thread
1. class Test extends Thread
2. {
3. public void run(){
4. System.out.println("running...");
5. } }
6. class Example
7. {
8. public static void main(String args[])
9. {
10. Test t1=new Test();
11. Test t2=new Test();
12. System.out.println("Name of t1:"+t1.getName());
13. System.out.println("Name of t2:"+t2.getName());
14.
15. t1.start();
16. t2.start();
17.
18. t1.setName("Sonoo Jaiswal");
19. System.out.println("After changing name of t1:"+t1.getName());
20. }
21. }
Test it Now
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
14. m2.setPriority(Thread.MAX_PRIORITY);
15. m1.start();
16. m2.start();
17. }
18. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Types of Exception
Multiple Catch
When more than one exception could be raised from a single piece of code
Specify more than one catch block
Each catch statement will be inspected in order
The first matching catch is selected and rest is bypassed
class Try1
{
public static void main(String args[])
{
int n;
try
{
Scnner s=new Scanner(System.in);
n= s.nextInt();
int a=50/n;
int c[]={1};
c[42]=99;
1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.