Java Unit-2
Java Unit-2
Page 1 of 25
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salar
y is:"+p.salary);
System.out.println("Bonus of Progra
mmer is:"+p.bonus);
}
class Employee{ }
float salary=40000;
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. We will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Page 2 of 25
There are five main types of inheritance in object-oriented programming:.
Single inheritance: This is the most common type of inheritance, where a child
class inherits from a single parent class.
Multilevel inheritance: This is a type of inheritance where a child class inherits
from another child class, which inherits from another child class, and so on.
Hierarchical inheritance: This is a type of inheritance where a parent class has
multiple child classes.
Multiple inheritance: This is a type of inheritance where a child class can inherit
from multiple parent classes.
Multiple inheritance is not supported in Java using classes. Hybrid inheritance: This is a
type of inheritance that combines two or more of the other types of inheritance
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Page 3 of 25
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
Page 4 of 25
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
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 TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}
Output:
meowing…
eating…
Multiple inheritance :-
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.
class A{
void msg(){System.out.println("Hello");}
Page 5 of 25
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
5. Hybrid Inheritance :-
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also
not possible with classes. In Java, we can achieve hybrid inheritance only
through Interfaces if we want to involve multiple inheritance to implement Hybrid
inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the
use of Multiple Inheritance exclusively. It can be achieved through a combination of
Multilevel Inheritance and Hierarchical Inheritance with classes, Hierarchical and Single
Inheritance with classes. Therefore, it is indeed possible to implement Hybrid inheritance
using classes alone, without relying on multiple inheritance type.
Page 6 of 25
Lets see this in a diagram:
It’s pretty clear with the diagram that in Multilevel inheritance there is a concept of
grand parent class. If we take the example of this diagram, then class C inherits class B
and class B inherits class A which means B is a parent class of C and A is a parent class of
B. So in this case class C is implicitly inheriting the properties and methods of class A
along with class B that’s what is called multilevel inheritance.
To learn the basics of inheritance refer this tutorial: Inheritance in Java
Multilevel Inheritance Example :-
In this example we have three classes – Car, Maruti and Maruti800. We have done a
setup – class Maruti extends Car and class Maruti800 extends Maruti. With the help
of this Multilevel hierarchy setup our Maruti800 class is able to use the methods of both
the classes (Car and Maruti).
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
Page 7 of 25
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
2.3 Explain method overriding and usage of super keyword.
Method Overriding in Java :-
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method overriding.
Page 8 of 25
Usage of Java Method Overriding :-
Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
Method overriding is used for runtime polymorphism
Let's understand the problem that we may face in the program if we don't use method
overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
Output: Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass
that is why we use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method are
the same, and there is IS-A relationship between the classes, so there is method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
Page 9 of 25
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
1. Output:
2. Bike is running safely
EXAMPLE-2 :-
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
Page 10 of 25
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
Page 11 of 25
}}
Output: black
white
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we
call eat() method from Dog class, it will call the eat() method of Dog class
by default because priority is given to local.
To call the parent class method, we need to use super keyword.
Page 12 of 25
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
2.4 Describe concept of Interfaces
An interface:
Interface looks like a class but is not a class.
An interface can have methods and variables just the like the class but the methods
declare by benefits abstract only method are in the body.
Also, the variables declared in an interface are public, static & final by default.
The use of interface in java:
Interfaces are used for all abstraction. Since methods in interfaces do not have body they
have to be implemented by the class before you can access them. The class that
implements interface must implement all the methods of that Interface
Syntax:
Interfaces are declared by specifying a keyword "Interface":
Interface Interface_name
{
public void method1 ();
public void method2();
}
Example of an Interface in Java :
This example shows how a class implements an interface. It has to provide body of all
the methods that are declared in interface.
Page 13 of 25
Public abstract void method1 (); Public abstract void method2 ();*/
Public void method1 ();
Public void method2 ();
2.5 DIFFERENCES BETWEEN ABSTRACT CLASSES AND INTERFACE:
1. Abstract class can have abstract and 1. Interface can have only abstract
non-abstract methods. methods Since Java 8, it can have
default and static methods also.
2. Abstract class doesn't support multiple
inheritance. 2. Interface supports multiple
inheritances.
3. Abstract class can have final, non- final,
static and non-static variables. 3. Interface has only static and final
variables
4. Abstract class can provide the
implementation of interface. 4. Interface can't provide the
implementation abstract class.
5. The abstract keyword is used to declare
abstract class. 5. The interface keyword is used to
declare interface.
6. An abstract class can extend another
java class and implement multiple java 6. An interface can extend another
interfaces. java interface only.
8. A java abstract class can have class 8. Members of a java interface are
members like private, protected, etc. public by default.
Page 14 of 25
void d();
}
Method of a interface
abstract class B implements A
{
public void ()
{
System.out.println("I am C");
}
}
of the methods
class M extends B
{
public void a(){System.out.println("I am a");}
public void b() {System.out.println("I am b");}
public void d() {System.out.println("I am d");}
}
class Test
{
public static void main(String args[])
{
A obj=new M();
obj.a();
obj.b();
obj.c();
obj.d();
}
}
Output:
I am a
I am b
I am c
I am d
2.8 EXPLAIN IMPLEMENTATION OF INTERFACES WITH SAMPLE PROGRAM:
Implementing Interface: It means creating a concrete class that implements an interface.
To implement an interface, we use the keyword
"Implements".
Syntax:
class concreteClass Implements InterfaceName
Page 15 of 25
Remember Concrete class must implement ALL methods of the interface.
Implementing class can have its own method.
Implementing class can extend a single super class or abstract class.
interface MyInterface
{
public void method1();
public void method2();
}
class Demo implements MyInterface
{
public void method1()
{
System.out.println(“implementation of method1”);
}
public void method2()
{
System.out.println(“ implementation of method”);
}
public static void main(String args[])
{
MyInterface obj =new Demo();
obj.method1 ();
}
}
Output:
Implementation of method1
Page 16 of 25
java.awt.event
java.sql
java.net
java.math
java
Page 17 of 25
{
System.out.println("Welcome to package");
}
}
The procedure to compile java package program:
If you are not using any IDE, you need to follow the syntax given below
Javac -d directory javafilename
For example javac -d Sample java
The -d switch specifies the destination where to put the generated class file.
If you want to keep the package within the same directory, you can use .(dot).
The procedure to run java package program:
1. You need to use fully qualified name.
e.g. mypack.Sample etc to run the class.
Syntax:
java packagename.classname
Ex: java mypack.Sample.
Output:
Welcome to package
Advantages 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.
•Provides a mechanism for class reuse.
•Java package removes naming collision.
2.8 EXPLAIN THE CONCEPT OF CLASS PATH
CLASSPATH:
•CLASSPATH is an environment variable which is used by Application ClassLoader to
locate and load the class files.
•The CLASSPATH defines the path, to find third-party and user-defined classes that are
not extensions or part of Java platform.
Include all the directories which contain class files and JAR files when setting the
CLASSPATH
You need to set the CLASSPATH if:
•You need to load a class that is not present in the current directory or any sub-
directories.
•You need to load a class that is not in a location specified by the extensions mechanism.
Note:
Page 18 of 25
1. The default value of CLASSPATH is a dot (.). It means the only current directory
Searched
2. The default value of CLASSPATH overrides when you set the CLASSPATH variable or
using the - classpath command (for short-cp).
There are two methods to set CLASSPATH:
1. By setting Environment Variable
2. Through Command Prompt
Method 1: Let's see how to set CLASSPATH by setting Environment Variable:
Step 1:
click on the Windows button and choose Control Panel. Select System.
Step 2:
Click on Advanced System Settings
Step 3:
A dialog box will open. Click on Environment Variables.
Step 4:
If the CLASSPATH already exists in System Variables, click on the Edit button then
put a semicolon (;) at the end. Paste the Path of Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button
and typeVariable name as CLASSPATH and Variable value as set
CLASSPATH=CLASSPATH:C:\Program Files\Java\jdk-19\bin; Remember: Put; at
the end of the CLASSPATH.
Method2:
Let's see how to set CLASSPATH by setting Through Command Prompt:
Type the following command in your Command Prompt and press enter.
set CLASSPATH=CLASSPATH: C:\Program Files\Java\jdk-19\bin;
In the above command, the set is an internal DOS command that allows the user
to change the variable value. CLASSPATH is a variable name. The variable
enclosed in percentage sign (%) is an existing environment variable. The
semicolon is a separator, and after the (;) there is the PATH of rt. jar file.
2.9 DESCRIBE CONCEPT OF ACCESS PROTECTION
Access Modifiers in Java
1. Private access modifier
2. Role of private constructor
3. Default access modifier
4. Protected access modifier
5. Public access modifier
6. Access Modifier with Method Overriding
Page 19 of 25
There are two types of modifiers in Java: access modifiers and non- access
modifiers.
The access modifiers in Java specify the accessibility or scope of a field, method
constructor, or class. We can change the access level of fields, constructors
methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private:
The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default:
The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected:
The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it canno be accessed from outside
the package.
4. Public:
The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package
PRIVATE:
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is a compile-time error
class A
private int data-40;
private void msg() {
System.out.println("Hello java"); }
public class Simple{
public static void main(String args[]){
A obj-new A();
System.out.println(obj.data);
Obj.msg();
}
Page 20 of 25
}
2) Default:
If you don't use any modifier, it is treated as default by default. The default
modifier is accessible only within package. It cannot be accessed from outside the
package. It provides more accessibility than private. But, it is more restrictive than
protected, and public.
Example of default access modifier:
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
package pack;
class A
void msg() (System.out.println("Hello");)
package mypack:
import pack.*;
class B{
public static void main(String args[]){
A ob) new A();
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package
3)Protected:
The protected access modifier is accessible within package and outside the package
but through inheritance only The protected access modifier can be applied on the
data member, method and constructor. It can't be applied on the class
It provides more accessibility than the default modifier.
Example of protected access modifier:-
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg() method of this
package is declared as protected, so it can be accessed from outside the class only
through Inheritance.
package pack;
Public class A{
protected void msg(){
System.out.println("Hello");
}
Page 21 of 25
}
package mypack;
import pack.*;
class B extends A
public static void main(String args[])
B obj new B();
obj.msg();
}
}
Output:Hello
4)Public:
The public access modifier is accessible everywhere.
It has the widest scope among all other modifiers.
Example of public access modifier.
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: hello
2.10 ILLUSTRATE THE MECHANISM OF IMPORTING PACKAGES:
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1. Using packagename.*
If you use package. then all the classes and interfaces of this package will be accessible but
not subpackages.
Page 22 of 25
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example of package that import the packagename.*:
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
Note: You compile the above A java as javac -d A java. Then automatically folder
named pack was created (where the A java file was stored) and A.class file also
automatically placed in that pack folder.
package mypack:
import pack.
class B{
public static void main(String args[]){
A obj =new A();
obj.msg():
}
}
Note:
1. You compile the above B. java as javac-d. Bijava Then automatically folder named
mypack was created (where the B java file was stored) and B.class file also automatically
placed in that mypack folder.
2. Run this program by using the command java mypack.B
Output:Hello
2. Using packagename.classname.
If you import package.classname then only declared class of this package will be
accessible.
Example of package by import package.classname.
package pack;
public class A{
public void msg() {
System.out.println("Hello");
}
}
Page 23 of 25
Package mypack;
import pack. A;
class B{
public static void main(String args[]){
A obj= new A();
Obj.msg();
}
}
Output:hello
3. Using fully qualified name.
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time
when you are accessing the class or interface.
It is generally used when two packages have same class name e g. java.util and java.sql
packages contain Date class
Example of package by import fully qualified name :-
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
package mypack;
class B{
public static void main(String args[]){
pack.A obj =new pack.A();//using fully qualified name
obj.msg();
}
}
Output:hello
2.11 DEVELOP SIMPLE APPLICATION TO DESIGN PACKAGES WITH SAMPLE
PROGRAMS.
While developing your project, you must follow some naming convention
regarding packages declaration, Let's take an example to understand the
convention.
See below a complete package structure of the project.
package com.ibm.hdfc.loan.homeloan;
While declaring the package name, every character should be lowercase
Page 24 of 25
Suppose you are working in IBM and the domain name of IBM is www.ibm.com.
You can declare the package by reversing the domain like this: package com.ibm;
where.
1. com It is generally company specification name and the folder starts with com which
is called root folder.
2. ibm Company name where the product is developed. It is the subfolder.
3. hdfc Client name for which we are developing our product or working for the
project.
4. loan Name of the project.
5. homeloan It is the name of the modules of the loan project. There are a number of
modules in the loan project like a Home loan, Car loan, or Personal loan. Suppose you
are working for Home loan module.
This is a complete packages structure like a professional which is adopted in the
company.
Another example is: package com.tcs.icici.loan.carloan.penalty.
Note: Keep in mind Root folder should be always the same for all the classes.
Page 25 of 25