java unit-2
java unit-2
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. In inheritance you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class and also you can add new methods and fields in your current.
In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
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.
Single Inheritance Example
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
1. class Animal{
2. void eat()
3. {
4. System.out.println("eating...");
5. } }
6. class Dog extends Animal
7. {
8. void bark()
9. {
10. System.out.println("barking...");
11. } }
12. class TestInheritance
13. {
14. public static void main(String args[])
15. {
16. Dog d=new Dog();
17. d.bark();
18. d.eat();
19. }}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark(){System.out.println("barking...");
11. }
12. }
13. class BabyDog extends Dog
14. {
15. void weep(){System.out.println("weeping...");
16. }
17. }
18. class TestInheritance2
19. {
20. public static void main(String args[])
21. {
22. BabyDog d=new BabyDog();
23. d.weep();
24. d.bark();
25. d.eat();
26. }}
Output:
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.
File: TestInheritance3.java
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class Cat extends Animal
16. {
17. void meow()
18. {
19. System.out.println("meowing...");
20. }
21. }
22. class TestInheritance3
23. {
24. public static void main(String args[]){
25. Cat c=new Cat();
26. c.meow();
27. c.eat();
28. //c.bark();//C.T.Error
29. }}
Output:
meowing...
eating...
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.
1. class Animal
2. {
3. String color="white";
4. }
5. class Dog extends Animal
6. {
7. String color="black";
8. void printColor()
9. {
10. System.out.println(color); //prints color of Dog class
11. System.out.println(super.color); //prints color of Animal class
12. }
13. }
14. class TestSuper1
15. {
16. public static void main(String args[])
17. {
18. Dog d=new Dog();
19. d.printColor();
20. }}
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void eat()
11. {
12. System.out.println("eating bread...");
13. }
14. void bark()
15. {
16. System.out.println("barking...");
17. }
18. void work()
19. {
20. super.eat();
21. bark();
22. }
23. }
24. class TestSuper2
25. {
26. public static void main(String args[])
27. {
28. Dog d=new Dog();
29. d.work();
30. }}
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
1. class Animal
2. {
3. Animal()
4. {
5. System.out.println("animal is created");
6. }
7. }
8. class Dog extends Animal
9. {
10. Dog()
11. {
12. super();
13. System.out.println("dog is created");
14. }
15. }
16. class TestSuper3
17. {
18. public static void main(String args[])
19. {
20. Dog d=new Dog();
21. }}
Preventing Inheritance
final is a keyword in java used for restricting some functionalities. We can declare
variables, methods, and classes with the final keyword. The main reason to
prevent inheritance is to make sure the way a class behaves is not corrupted by a subclass.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run()
4. {
5. speedlimit=400;
6. }
7. public static void main(String args[]){
8. Bike9 obj=new Bike9();
9. obj.run();
10. }
11. }//end of class
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any
type like Employee, Student etc, we can use Object class reference to refer that object. For
example:
Object obj=getObject ();//we don't know what object will be returned from this method
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.
Method Description
returns the Class class object of this object. The Class
public final Class getClass() class can further be used to get the metadata of this
class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.
public final void wait()throws causes the current thread to wait, until another thread
InterruptedException notifies (invokes notify() or notifyAll() method).
POLYMORPHISM
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance. This allows us to perform a single action in different
ways.
class Animal {
class Main {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an
instance of Animal.So compiler doesn't know its type, only its base type.
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.
1. Same Method Name: The overriding method in the subclass must have the same
name as the method in the superclass that it is overriding.
2. Same Parameters: The overriding method must have the same number and types of
parameters as the method in the superclass. This ensures compatibility and
consistency with the method signature defined in the superclass.
3. IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship
between the subclass and the superclass. This means that the subclass must inherit
from the superclass, either directly or indirectly, to override its methods.
4. Same Return Type or Covariant Return Type: The return type of the overriding
method can be the same as the return type of the overridden method in the superclass,
or it can be a subtype of the return type in the superclass. This is known as the
covariant return type, introduced in Java 5.
5. Access Modifier Restrictions: The access modifier of the overriding method must be
the same as or less restrictive than the access modifier of the overridden method in the
superclass. Specifically, a method declared as public in the superclass can be
overridden as public or protected but not as private. Similarly, a method declared as
protected in the superclass can be overridden as protected or public but not as private.
A method declared as default (package-private) in the superclass can be overridden
with default, protected, or public, but not as private.
6. No Final Methods: Methods declared as final in the superclass cannot be overridden
in the subclass. This is because final methods cannot be modified or extended.
7. No Static Methods: Static methods in Java are resolved at compile time and cannot
be overridden. Instead, they are hidden in the subclass if a method with the same
signature is defined in the subclass.
1. class Vehicle
2. {
3. void run()
4. {
5. System.out.println("Vehicle is running");
6. }
7. }
8. class Bike2 extends Vehicle
9. {
10. void run()
11. {
12. System.out.println("Bike is running safely");
13. }
14. public static void main(String args[])
15. {
16. Bike2 obj = new Bike2();
17. obj.run();
18. }
19. }
class Bank
1. {
2. int getRateOfInterest()
3. {
4. return 0;
5. }
6. }
7. class SBI extends Bank
8. {
9. int getRateOfInterest()
10. {
11. return 8;
12. }
13. }
14.
15. class ICICI extends Bank
16. {
17. int getRateOfInterest()
18. {
19. return 7;
20. }
21. }
22. class AXIS extends Bank
23. {
24. int getRateOfInterest()
25. {
26. return 9;
27. }
28. }
29. class Test2
30. {
31. public static void main(String args[])
32. {
33. SBI s=new SBI();
34. ICICI i=new ICICI();
35. AXIS a=new AXIS();
36. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
37. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
38. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
39. }
40. }
Output:
INTERFACES:
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.
4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Output:
I am a
I am b
I am c
I am d
INTERFACE:
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
Interfaces can have abstract methods and variables. It cannot have a method body.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Example:
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.
The access specifiers used with classes are In Interface only one specifier is used-
private, protected, and public. Public.
IMPLEMENTATION:
import java.io.*;
// A simple interface
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Output
Geek
10
// Interface 1
interface API {
// Default method
default void show()
{
// Print statement
System.out.println("Default API");
}
}
// Interface 2
// Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}
// Interface 3
// Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}
// Main class
// Implementation class code
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass d = new TestClass();
Output
Default API
Display from Interface1
Print from Interface2
Extending Interfaces
One interface can inherit another by the use of keyword extends. When a class implements
an interface that inherits another interface, it must provide an implementation for all
methods required by the interface inheritance chain.
Program 1:
Java
interface A {
void method1();
void method2();
}
// B now includes method1 and method2
interface B extends A {
void method3();
}
// the class must implement all method of A and B.
class gfg implements B {
public void method1()
{
System.out.println("Method 1");
}
public void method2()
{
System.out.println("Method 2");
}
public void method3()
{
System.out.println("Method 3");
}
}
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.
Additionally, it can access all the members of the outer class, including private data members
and methods.
Sometimes users need to program a class in such a way so that no other class can access it.
Therefore, it would be better if you include it within other classes.
If all the class objects are a part of the outer object then it is easier to nest that class inside the
outer class. That way all the outer class can access all the objects of the inner class.
Type Description
Member Inner Class A class created within class and outside method.
Static Nested Class A static class was created within the class.
There are certain advantages associated with inner classes are as follows:
Making code clean and readable.
Private methods of the outer class can be accessed, so bringing a new dimension and
making it closer to the real world.
Optimizing the code module.
Types of Inner Classes
There are basically four types of inner classes in java.
1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes
// Class 1
// Helper classes
class Outer {
// Class 2
// Simple nested inner class
class Inner {
// Print statement
System.out.println("In a nested class method");
}
}
}
// Class 2
// Main class
class Main {
Output
In a nested class method
Note: We can not have a static method in a nested inner class because an inner class is
implicitly associated with an object of its outer class so it cannot define any static method
for itself.
// Class 1
// Outer class
class Outer {
// Method
private static void outerMethod()
{
// Print statement
System.out.println("inside outerMethod");
}
// Class 2
// Static inner class
static class Inner {
// Print statement
System.out.println("inside inner class Method");
// Calling method static display method rather than an instance of that class.
Outer.Inner.display();
}
}
Output
inside inner class Method
inside outerMethod
Anonymous Inner Classes
Anonymous inner classes are declared without any name at all. They are created in two
ways.
As a subclass of the specified type
As an implementer of the specified interface
Way 1: As a subclass of the specified type
Example:
Java
// Java Program to Illustrate Anonymous Inner classes
// Declaration Without any Name
// As a subclass of the specified type
// Class 1
// Helper class
class Demo {
// Class 2
// Main class
class Flavor1Demo {
// An anonymous class with Demo as base class
static Demo d = new Demo() {
// Method 1
// show() method
void show()
{
// Calling method show() via super keyword
// which refers to parent class
super.show();
// Print statement
System.out.println("i am in Flavor1Demo class");
}
};
// Method 2
// Main driver method
public static void main(String[] args)
{
// Calling show() method inside main() method
d.show();
}
}
Output
i am in show method of super class
i am in Flavor1Demo class
Java Package
1. Java Package
2. Example of package
3. Accessing package
1. By import packagename.*
2. By import packagename.classname
3. By fully qualified name
4. Subpackage
5. Sending class file to another directory
6. -classpath switch
7. 4 ways to load the class file or jar file
8. How to put two public class in a package
9. Static Import
10. Package class
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represen
current folder.
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.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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.
Output:Hello
CLASSPATH in Java
import java.io.*;
// Main class
class GFG {
{
// Print statement
Output
8. Select OK.
Set the CLASSPATH on Linux
Command Line:
Find out where you have installed Java, basically, it’s in /usr/lib/jvm path. Set the
CLASSPATH in /etc/environment using
sudo <editor name> /etc/environment
Add the following lines,
CLASSPATH=".:/path/to/your/classes:/path/to/your/libraries"
export CLASSPATH
Note: Colon (:) is used as a separate directory and dot (.) is the default value of
CLASSPATH in the above command.
To check the current CLASSPATH, run
echo ${CLASSPATH}
Difference between PATH and CLASSPATH
The PATH variable is used to specify the location of the Java binaries (e.g., java,
javac). It allows the system to locate the Java executables to compile and run programs.
The CLASSPATH variable is used to specify the location of the Java class files and
libraries required for the program. It tells the JVM and compiler where to look for user-
defined classes and packages.