Unit 2
Unit 2
1. Inheritance
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object.
The idea behind inheritance in Java is that 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. Moreover, you can add new methods and fields in your current
class also.
Syntax of Inheritance
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.
Diagram
Example
class Animal {
// to perform inheritance
Example
class Employee{
float salary=40000;
int bonus=10000;
Output:
1. Single inheritance.
2. Multi-level inheritance.
3. Multiple inheritance.
4. Hierarchical Inheritance.
5. Hybrid Inheritance.
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
1. Single Inheritance
Example Program
class Animal{
void eat(){
System.out.println("eating...");}
void bark(){
System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
Output
barking...
eating...
2. Multilevel Inheritance
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.
Example Program
class Animal{
void eat(){
System.out.println("eating...");}
void bark(){
System.out.println("barking...");}
void weep(){
System.out.println("weeping...");}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
Output
weeping...
barking...
eating...
3. Hierarchical Inheritance
Example Program
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...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
class TestInheritance3{
c.meow();
c.eat();
Output
meowing...
eating...
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.
Example Program
class Animal{
String color="white";
String color="black";
void printColor(){
class TestSuper1{
d.printColor();
}}
Program Explanation:
In the above example, Animal and Dog both classes have a common property
color. If we print color property, it will print the color of current class by
default. To access the parent property, we need to use super keyword.
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.
Example Program
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
class TestSuper2{
d.work();
}}
Program Explanation:
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.
The super keyword can also be used to invoke the parent class constructor.
Example Program
class Animal{
Animal(){System.out.println("animal is created");}
Dog(){
super();
System.out.println("dog is created");
class TestSuper3{
}}
The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).
1. variable
2. method
3. class
1. final variable:
To declare a final variable in Java, the keyword "final" is used before the
variable declaration.
class Bike{
void run(){
speedlimit=400;
obj.run();
}//end of class
Output:
In above program there is a final variable speedlimit, we are going to change the
value of this variable, but It can't be changed because final variable once
assigned a value can never be changed.
2. final method
To declare a method as final in Java, the keyword "final" is used before the
method signature.
class Bike{
honda.run();
Output:
To declare a class as final in Java, the keyword "final" is used before the class
declaration.
void run(){
honda.run();
Output:
5. Polymorphism in Java
Polymorphism in Java is the task that performs 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.
Example Program
class Shapes {
class Main {
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
Output
The formula for the area of the Circle is 3.14 * radius * radius
1. Method Overloading
If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
class Adder{
class TestOverloading1{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output: 22 33
class TestOverloading2{
System.out.println(Adder.add(12.3,12.6));
}}
Output: 22 24.9
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
Example Program
class Bank{
}
class AXIS extends Bank{
class Test{
Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
Abstraction
It shows only essential things to the user and hides the internal details.
abstract classA{ }
obj.run();
class TestBank{
Bank b;
b=new SBI();
b=new PNB();
}}
8. Interfaces in JAVA
The interface in Java is a mechanism to achieve abstraction.
There can be only abstract methods in the Java interface, not method body.
Interfaces can have abstract methods and variables. It cannot have a method
body.
Syntax
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
//In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
interface printable{
void print();
obj.print();
Output: Hello
interface Printable{
void print();
interface Showable{
void show();
}
class A7 implements Printable,Showable{
obj.print();
obj.show();
Output
Hello
Welcome
The interface that extends another interface has its own members and all the
members defined in its parent interface too.
The class which implements a child interface needs to provide code for the
methods defined in both child and parent interfaces, otherwise, it needs to be
defined as abstract class.
Example Program
interface ParentInterface{
void parentMethod();
void childMethod();
}
class A implements ChildInterface{
obj.childMethod();
obj.parentMethod();
Inner classes are also known as nested classes because they are nested within
another class.
Inner classes can access the members of the enclosing class (outer class) as if
they were their own members.
This means that an inner class can access the private fields and methods of the
outer class.
Inner classes provide a way to logically group classes and interfaces in one
place and can increase encapsulation and code readability.
2. Static Nested Class: This is a static inner class that is declared inside a
class using the static keyword. It can access only the static members of
the enclosing class.
//code
class Java_Inner_class{
//code
}
}
Example Program
class OuterClass
int x = 10;
class InnerClass
int y = 5;
System.out.println(outerobj.x);
System.out.println(innerobj.y);
}
}
Output: 10 5
The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole package
that contain all the classes that belong to the specified package.
Syntax
//save as Simple.java
package mypack;
System.out.println("Welcome to package");
} }
Compilation:
The -d switch specifies the destination where to put the generated class file.
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.
Types of Packages
1. Built-in Packages
The Java API is a library of predefined classes that are free to use, included in
the Java Development Environment.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
These are the packages that are defined by the user. First we create a directory
myPackage (name should be same as the name of the package). Then create the
MyClass inside the directory with the first statement being the package names.
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.
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.*;
class B{
obj.msg();
} }
Compilation
Run commnd:
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
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
import pack.A;
class B{
obj.msg();
Output:Hello
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
//save by A.java
package pack;
public class A{
//save by B.java
package mypack;
class B{
obj.msg();
Output: Hello