SlideShare a Scribd company logo
UNIT II
Inheritance in Java
* Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of
OOPs(Object Oriented programming system).
* 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.Inheritance represents the IS-A relationship which is also known as
a parent-child relationship
Why use inheritance in java
o 1.For Method Overriding
---→(so runtime polymorphism can be achieved).
2. For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.
class Subclass-name extends Superclass-name
{
//methods and fields
}
Note: 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
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It
means that Programmer is a type of Employee.
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. We will learn about interfaces later.
Basics to java programming and concepts of java
Basics to java programming and concepts of java
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance.
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[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance
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();
}}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as 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();
//c.bark();//C.T.Error
}}
super key word
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.
Usage of Java super Keyword
* super can be used to refer immediate parent class instance variable.
* super can be used to invoke immediate parent class method.
* super() can be used to invoke immediate parent class constructor.
class Animal {
public void move() {
System.out.println("Animals
can move");
}
public void eat()
{
System.out.println(" Animals
Will eat.");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class
method
System.out.println("Dogs can walk and run");
super.eat();
}
}
public class TestDog {
public static void main(String args[]) {
Dog d=new Dog();
d.move();
Animal obj = new Dog(); // Animal reference
but Dog object
obj.move(); // runs the method in Dog class
}
}
Preventing inheritance
While one of Java's strengths is the concept of inheritance, in which one class
can derive from another, sometimes it's desirable to prevent inheritance by
another class. To prevent inheritance, use the keyword "final" when creating
the class.
Why Prevent Inheritance?
The main reason to prevent inheritance is to make sure the way a class behaves
is not corrupted by a subclass.
public final class Account
{
statements
}
Suppose we have a class Account and a subclass that extends it,
OverdraftAccount. Class Account has a method getBalance()
This means that the Account class cannot be a superclass, and the OverdraftAccount class can
no longer be its subclass.
Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption
by a subclass. For example, OverdraftAccount still could be a subclass of Account, but it should
be prevented from overriding the getBalance() method.
public class Account {
private double balance;
public final double getBalance()
{
return this.balance;
}
}
final is a non-access modifier for Java elements. The final modifier is used for
finalizing the implementations of classes, methods, and variables.
What are ways to Prevent Inheritance in Java Programming?
There are 2 ways to stop or prevent inheritance in Java programming.
By using final keyword with a class orBy using a private constructor in a class.
Final Keyword In Java
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
The final keyword can be applied with the variables, a final variable that have
no value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only.
Java final variable
If you make any variable as final, you cannot change the value of final variable(It
will be constant)
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
63.151/Bike9.java:4: error: cannot assign a value to final variable
speedlimit
speedlimit=400;
^
1 error
Java final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Compile by: javac Honda.java
63.151/Honda.java:6: error: run() in Honda cannot override run() in Bike with 100kmph");}
^
overridden method is final
1 error
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Compile by: javac Honda1.java
3.133/Honda1.java:3: error: cannot inherit from final Bike class Honda1
extends Bike{}
Polymorphism
Polymorphism is briefly described as “one interface, many
implementations”.
Polymorphism in Java is a concept by which we can perform a single action
in different ways.
1. Compile time polymorphism
2. Run time polymorphism
Compile time polymorphism is method overloading whereas Runtime time
polymorphism is done using inheritance and interface.
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.
Rules for Java Method Overriding
1.The method must have the same name as in the parent class
2.The method must have the same parameter as in the parent class.
3.There must be an IS-A relationship (inheritance).
class Vehicle
{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
} } OUT PUT: Bike is running safely
In Java, runtime polymorphism or dynamic method dispatch is a process in
which a call to an overridden method is resolved at runtime rather than at
compile-time. In this process, an overridden method is called through the
reference variable of a superclass.
class Car {
void run()
{ System.out.println(“car is running”); }
}
class Audi extends Car {
void run()
{ System.out.prinltn(“Audi is running safely with
100km”); }
public static void main(String args[])
{
Car b= new Audi(); //upcasting
b.run();
} }
Since method invocation is
determined by the JVM not
compiler, it is known as
runtime polymorphism.
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest:
"+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest:
"+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest:
"+b.getRateOfInterest());
}
}
Java Abstract Class and Abstract Methods
A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract (method with out body) and non-abstract
methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
There are two ways to achieve abstraction in java
1.Abstract class (0 to 100%)
2.Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
Points to Remember
•An abstract class must be declared with an abstract keyword.
•It can have abstract and non-abstract methods.
•It cannot be instantiated.
•It can have constructors and static methods also.
•It can have final methods which will force the subclass not to change
the body of the method.
1.abstract class A{}
Abstract Method in Java
A method which is declared as abstract and does not have implementation is
known as an abstract method.
1.abstract void printStatus();//no method body and abstract
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
} OUT PUT : running safely
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1
s.draw();
}
} output: drawing circle
Abstract class having constructor, data member and
methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
bike is created
running safely..
gear changed
Interface
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
An interface in Java is similar to class. It is a collection of abstract methods.
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.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
A class implements an interface, thereby inheriting the abstract methods of the interface.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Why use Java interface?
1) It is used to achieve abstraction.
2) By interface, we can support the functionality of multiple inheritance.
How to declare an interface?
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.
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
A class extends another class, an interface extends another interface, but
a class implements an interface.
interface inter
{
int a=10,b=20;
public void add();
}
class c1 implements inter
{
public void add()
{
int sum=a+b;
System.out.println("Sum of numbers is:" +sum);
}
public static void main(String[] srgs)
{
c1 obj= new c1();
obj.add();
}
} output: Sum of numbers is: 30
interface Drawable{
void draw();
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
Drawable d1=new Rectangle();
d1.draw();
}} output: drawing circle
drawing rectangle
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface inter
{
int a=10,b=20;
public abstract void add();
}
interface inter1
{
int c=20,d=10;
public abstract void sub();
}
class c1 implements inter,inter1
{
public void add()
{
int sum=a+b;
System.out.println(" Sum of numbers
is :" +sum);
}
public void sub()
{
int r=c-d;
System.out.println(" Difference of numbers
is :" +r);
}
public static void main(String[] args)
{
c1 obj=new c1();
obj.add();
obj.sub();
}
} Output: Sum of numbers is : 30
Difference of numbers is: 10
Interface inheritance
A class implements an interface, but one interface extends another
interface. interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
} Out put : Hello
} Welcome
Java Nested Interface
An interface, i.e., declared within another interface or class, is known as a nested
interface. The nested interfaces are used to group related interfaces so that they
can be easy to maintain.
Points to remember
•The nested interface must be public if it is declared inside the interface, but it
can have any access modifier if declared within the class.
•Nested interfaces are declared static
interface interface_name{
...
interface nested_interface_name{
...
}
}
Syntax of nested interface which is declared within the interface
Syntax of nested interface which is declared within the class
class class_name{
...
interface nested_interface_name{
...
}
}
Example of nested interface which is declared within the interface
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class c1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public void show()
{
System.out.println("Welcome to nested interface");
}
public static void main(String args[])
{
c1 obj1=new c1();
obj1.msg();
obj1.show();
}
}
Output: Hello nested interface
Welcome to nested interface
Example of nested interface which is declared within the class
class A
{
interface Message
{
void msg();
void show();
}
}
class inter implements A.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public void show()
{
System.out.println(" Welcome to nested interface");
}
public static void main(String args[]){
inter obj1=new inter();
obj1.show();
obj1.msg();
}
}
Output: Welcome to nested interface
Hello nested interface
Java Default Methods
Java provides a facility to create default methods inside the interface. Methods
which are defined inside the interface and tagged with default are known as default
methods. These methods are non-abstract methods.
interface add
{
public void addition();
default void addition1()
{ int a=1,b=2,c;
c=a+b;
System.out.println(c);
}
static void sub()
{
int l=20,m=10,n;
n=l-m;
System.out.println(n);
}
}
class c1 implements add{
public void addition()
{
int i=1,j=4,k;
k=i+j;
System.out.println(k); }
public static void main(String[] args)
{ add obj=new c1();
obj.addition();
obj.addition1();
add.sub();
}
} output:5
3
10
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can have default
and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static
variables.
Interface has only static and final variables.
4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement
multiple Java interfaces.
An interface can extend another Java interface only.
7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements".
8) A Java abstract class can have class members like private,
protected, etc.
Members of a Java interface are public by default.
9)Example:public abstract clasShape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
Java Package
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.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
1. Core Packages: Core Packages are predefined
packages given by Sun MicroSystems which begin with
“java”.
2. Extended Packages: Extended packages are also
predefined packages given by Sun Microsystems which
begin with “javax”.
3. Third-Party Packages: Third-Party Packages are also
predefined packages that are given by some other
companies as a part of Java Software.
Example:oracle.jdbc, com.mysql, etc
User-Defined Packages in Java
In Java, we can also create user-defined packages according to our
requirements. To create the user-defined packages we have to use a java
keyword called “package.
Rules:
1. While writing the package name we can specify packages in any number of
levels but specifying one level is mandatory.
2. The package statement must be written as the first executable statement in
the program.
3. We can write at most one package statement in the program
package Demo;
public class PackageDemo {
public static void main(String args[]) {
System.out.println("Have a Nice
Day...!!!");
}
}
How to access package from another package?
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{
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();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will
be accessible.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
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.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
C:UsersMRUHDesktopjavaexpackage>java pack.Simple
C:UsersMRUHDesktopjavaexpackage>javac -d . B.java
Subpackage in java
Package inside the package is called the subpackage. It should be created to
categorize the package further.
package pack.package;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
Ad

More Related Content

Similar to Basics to java programming and concepts of java (20)

Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
sonukumarjha12
 
web program-Inheritance,pack&except in Java.ppt
web program-Inheritance,pack&except in Java.pptweb program-Inheritance,pack&except in Java.ppt
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
Inheritance & interface ppt Inheritance
Inheritance & interface ppt  InheritanceInheritance & interface ppt  Inheritance
Inheritance & interface ppt Inheritance
narikamalliy
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
BHUVIJAYAVELU
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
manish kumar
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
Inheritance in Java is a mechanism in which one object acquires all the prope...
Inheritance in Java is a mechanism in which one object acquires all the prope...Inheritance in Java is a mechanism in which one object acquires all the prope...
Inheritance in Java is a mechanism in which one object acquires all the prope...
Kavitha S
 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptx
DrYogeshDeshmukh1
 
Inheritance in Java.pdf
Inheritance in Java.pdfInheritance in Java.pdf
Inheritance in Java.pdf
kumari36
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Hamid Ghorbani
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
naeemcse
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
CurativeServiceDivis
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
web program-Inheritance,pack&except in Java.ppt
web program-Inheritance,pack&except in Java.pptweb program-Inheritance,pack&except in Java.ppt
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
Inheritance & interface ppt Inheritance
Inheritance & interface ppt  InheritanceInheritance & interface ppt  Inheritance
Inheritance & interface ppt Inheritance
narikamalliy
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
SakkaravarthiS1
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
manish kumar
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
Kalai Selvi
 
Inheritance in Java is a mechanism in which one object acquires all the prope...
Inheritance in Java is a mechanism in which one object acquires all the prope...Inheritance in Java is a mechanism in which one object acquires all the prope...
Inheritance in Java is a mechanism in which one object acquires all the prope...
Kavitha S
 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptx
DrYogeshDeshmukh1
 
Inheritance in Java.pdf
Inheritance in Java.pdfInheritance in Java.pdf
Inheritance in Java.pdf
kumari36
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
naeemcse
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 

Recently uploaded (20)

Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning ModelsMode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Mode-Wise Corridor Level Travel-Time Estimation Using Machine Learning Models
Journal of Soft Computing in Civil Engineering
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
How to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdfHow to Buy Snapchat Account A Step-by-Step Guide.pdf
How to Buy Snapchat Account A Step-by-Step Guide.pdf
jamedlimmk
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
Ad

Basics to java programming and concepts of java

  • 2. Inheritance in Java * Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs(Object Oriented programming system). * 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.Inheritance represents the IS-A relationship which is also known as a parent-child relationship
  • 3. Why use inheritance in java o 1.For Method Overriding ---→(so runtime polymorphism can be achieved). 2. For Code Reusability. Terms used in Inheritance Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • 4. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. class Subclass-name extends Superclass-name { //methods and fields } Note: 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
  • 5. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
  • 6. 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. We will learn about interfaces later.
  • 9. Single Inheritance Example When a class inherits another class, it is known as a single inheritance. 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[]){ Dog d=new Dog(); d.bark(); d.eat(); }}
  • 10. Multilevel Inheritance Example When there is a chain of inheritance, it is known as multilevel inheritance 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(); }}
  • 11. Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as 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(); //c.bark();//C.T.Error }}
  • 12. super key word The super keyword in Java is a reference variable which is used to refer immediate parent class object. Usage of Java super Keyword * super can be used to refer immediate parent class instance variable. * super can be used to invoke immediate parent class method. * super() can be used to invoke immediate parent class constructor.
  • 13. class Animal { public void move() { System.out.println("Animals can move"); } public void eat() { System.out.println(" Animals Will eat."); } } class Dog extends Animal { public void move() { super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); super.eat(); } } public class TestDog { public static void main(String args[]) { Dog d=new Dog(); d.move(); Animal obj = new Dog(); // Animal reference but Dog object obj.move(); // runs the method in Dog class } }
  • 14. Preventing inheritance While one of Java's strengths is the concept of inheritance, in which one class can derive from another, sometimes it's desirable to prevent inheritance by another class. To prevent inheritance, use the keyword "final" when creating the class. Why Prevent Inheritance? The main reason to prevent inheritance is to make sure the way a class behaves is not corrupted by a subclass.
  • 15. public final class Account { statements } Suppose we have a class Account and a subclass that extends it, OverdraftAccount. Class Account has a method getBalance() This means that the Account class cannot be a superclass, and the OverdraftAccount class can no longer be its subclass. Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption by a subclass. For example, OverdraftAccount still could be a subclass of Account, but it should be prevented from overriding the getBalance() method.
  • 16. public class Account { private double balance; public final double getBalance() { return this.balance; } } final is a non-access modifier for Java elements. The final modifier is used for finalizing the implementations of classes, methods, and variables.
  • 17. What are ways to Prevent Inheritance in Java Programming? There are 2 ways to stop or prevent inheritance in Java programming. By using final keyword with a class orBy using a private constructor in a class. Final Keyword In Java 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
  • 18. The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. Java final variable If you make any variable as final, you cannot change the value of final variable(It will be constant)
  • 19. class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } } 63.151/Bike9.java:4: error: cannot assign a value to final variable speedlimit speedlimit=400; ^ 1 error
  • 20. Java final method If you make any method as final, you cannot override it. class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Compile by: javac Honda.java 63.151/Honda.java:6: error: run() in Honda cannot override run() in Bike with 100kmph");} ^ overridden method is final 1 error
  • 21. Java final class If you make any class as final, you cannot extend it. final class Bike{} class Honda1 extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } } Compile by: javac Honda1.java 3.133/Honda1.java:3: error: cannot inherit from final Bike class Honda1 extends Bike{}
  • 22. Polymorphism Polymorphism is briefly described as “one interface, many implementations”. Polymorphism in Java is a concept by which we can perform a single action in different ways. 1. Compile time polymorphism 2. Run time polymorphism Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.
  • 23. 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. Rules for Java Method Overriding 1.The method must have the same name as in the parent class 2.The method must have the same parameter as in the parent class. 3.There must be an IS-A relationship (inheritance).
  • 24. class Vehicle { void run(){ System.out.println("Vehicle is running"); } } class Bike2 extends Vehicle{ void run() { System.out.println("Bike is running safely"); } public static void main(String args[]){ Bike2 obj = new Bike2();//creating object obj.run();//calling method } } OUT PUT: Bike is running safely
  • 25. In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. class Car { void run() { System.out.println(“car is running”); } } class Audi extends Car { void run() { System.out.prinltn(“Audi is running safely with 100km”); } public static void main(String args[]) { Car b= new Audi(); //upcasting b.run(); } } Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
  • 26. class Bank{ float getRateOfInterest(){return 0;} } class SBI extends Bank{ float getRateOfInterest(){return 8.4f;} } class ICICI extends Bank{ float getRateOfInterest(){return 7.3f;} } class AXIS extends Bank{ float getRateOfInterest(){return 9.7f;} } class TestPolymorphism{ public static void main(String args[]){ Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); } }
  • 27. Java Abstract Class and Abstract Methods A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract (method with out body) and non-abstract methods (method with the body). Abstraction in Java Abstraction is a process of hiding the implementation details and showing only functionality to the user. There are two ways to achieve abstraction in java 1.Abstract class (0 to 100%) 2.Interface (100%)
  • 28. Abstract class in Java A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated. Points to Remember •An abstract class must be declared with an abstract keyword. •It can have abstract and non-abstract methods. •It cannot be instantiated. •It can have constructors and static methods also. •It can have final methods which will force the subclass not to change the body of the method. 1.abstract class A{}
  • 29. Abstract Method in Java A method which is declared as abstract and does not have implementation is known as an abstract method. 1.abstract void printStatus();//no method body and abstract abstract class Bike{ abstract void run(); } class Honda4 extends Bike{ void run(){System.out.println("running safely");} public static void main(String args[]){ Bike obj = new Honda4(); obj.run(); } } OUT PUT : running safely
  • 30. abstract class Shape{ abstract void draw(); } //In real scenario, implementation is provided by others i.e. unknown by end user class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle1 extends Shape{ void draw(){System.out.println("drawing circle");} } //In real scenario, method is called by programmer or user class TestAbstraction1{ public static void main(String args[]){ Shape s=new Circle1 s.draw(); } } output: drawing circle
  • 31. Abstract class having constructor, data member and methods abstract class Bike{ Bike(){System.out.println("bike is created");} abstract void run(); void changeGear(){System.out.println("gear changed");} } class Honda extends Bike{ void run(){System.out.println("running safely..");} } class TestAbstraction2{ public static void main(String args[]){ Bike obj = new Honda(); obj.run(); obj.changeGear(); } } bike is created running safely.. gear changed
  • 32. Interface An interface in Java is a blueprint of a class. It has static constants and abstract methods. An interface in Java is similar to class. It is a collection of abstract methods. 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. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class.
  • 33. A class implements an interface, thereby inheriting the abstract methods of the interface. Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. Why use Java interface? 1) It is used to achieve abstraction. 2) By interface, we can support the functionality of multiple inheritance.
  • 34. How to declare an interface? 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. interface <interface_name> { // declare constant fields // declare methods that abstract // by default. }
  • 35. The relationship between classes and interfaces A class extends another class, an interface extends another interface, but a class implements an interface.
  • 36. interface inter { int a=10,b=20; public void add(); } class c1 implements inter { public void add() { int sum=a+b; System.out.println("Sum of numbers is:" +sum); } public static void main(String[] srgs) { c1 obj= new c1(); obj.add(); } } output: Sum of numbers is: 30
  • 37. interface Drawable{ void draw(); } class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle(); d.draw(); Drawable d1=new Rectangle(); d1.draw(); }} output: drawing circle drawing rectangle
  • 38. Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
  • 39. interface inter { int a=10,b=20; public abstract void add(); } interface inter1 { int c=20,d=10; public abstract void sub(); } class c1 implements inter,inter1 { public void add() { int sum=a+b; System.out.println(" Sum of numbers is :" +sum); } public void sub() { int r=c-d; System.out.println(" Difference of numbers is :" +r); } public static void main(String[] args) { c1 obj=new c1(); obj.add(); obj.sub(); } } Output: Sum of numbers is : 30 Difference of numbers is: 10
  • 40. Interface inheritance A class implements an interface, but one interface extends another interface. interface Printable{ void print(); } interface Showable extends Printable{ void show(); } class TestInterface4 implements Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show(); } Out put : Hello } Welcome
  • 41. Java Nested Interface An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. Points to remember •The nested interface must be public if it is declared inside the interface, but it can have any access modifier if declared within the class. •Nested interfaces are declared static
  • 42. interface interface_name{ ... interface nested_interface_name{ ... } } Syntax of nested interface which is declared within the interface Syntax of nested interface which is declared within the class class class_name{ ... interface nested_interface_name{ ... } }
  • 43. Example of nested interface which is declared within the interface interface Showable { void show(); interface Message { void msg(); } } class c1 implements Showable.Message { public void msg() { System.out.println("Hello nested interface"); } public void show() { System.out.println("Welcome to nested interface"); } public static void main(String args[]) { c1 obj1=new c1(); obj1.msg(); obj1.show(); } } Output: Hello nested interface Welcome to nested interface
  • 44. Example of nested interface which is declared within the class class A { interface Message { void msg(); void show(); } } class inter implements A.Message { public void msg() { System.out.println("Hello nested interface"); } public void show() { System.out.println(" Welcome to nested interface"); } public static void main(String args[]){ inter obj1=new inter(); obj1.show(); obj1.msg(); } } Output: Welcome to nested interface Hello nested interface
  • 45. Java Default Methods Java provides a facility to create default methods inside the interface. Methods which are defined inside the interface and tagged with default are known as default methods. These methods are non-abstract methods. interface add { public void addition(); default void addition1() { int a=1,b=2,c; c=a+b; System.out.println(c); } static void sub() { int l=20,m=10,n; n=l-m; System.out.println(n); } } class c1 implements add{ public void addition() { int i=1,j=4,k; k=i+j; System.out.println(k); } public static void main(String[] args) { add obj=new c1(); obj.addition(); obj.addition1(); add.sub(); } } output:5 3 10
  • 46. Difference between abstract class and interface Abstract class Interface 1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) An abstract class can extend another Java class and implement multiple Java interfaces. An interface can extend another Java interface only. 7) An abstract class can be extended using keyword "extends". An interface can be implemented using keyword "implements". 8) A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default. 9)Example:public abstract clasShape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); }
  • 47. Java Package 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. Advantage of Java Package 1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision.
  • 48. The package keyword is used to create a package in java. //save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }
  • 49. 1. Core Packages: Core Packages are predefined packages given by Sun MicroSystems which begin with “java”. 2. Extended Packages: Extended packages are also predefined packages given by Sun Microsystems which begin with “javax”. 3. Third-Party Packages: Third-Party Packages are also predefined packages that are given by some other companies as a part of Java Software. Example:oracle.jdbc, com.mysql, etc
  • 50. User-Defined Packages in Java In Java, we can also create user-defined packages according to our requirements. To create the user-defined packages we have to use a java keyword called “package.
  • 51. Rules: 1. While writing the package name we can specify packages in any number of levels but specifying one level is mandatory. 2. The package statement must be written as the first executable statement in the program. 3. We can write at most one package statement in the program package Demo; public class PackageDemo { public static void main(String args[]) { System.out.println("Have a Nice Day...!!!"); } }
  • 52. How to access package from another package? 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.
  • 53. //save by A.java package pack; 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(); } }
  • 54. 2) Using packagename.classname If you import package.classname then only declared class of this package will be accessible. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.A; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
  • 55. 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. //save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; class B{ public static void main(String args[]){ pack.A obj = new pack.A();//using fully qualified name obj.msg(); } }
  • 57. Subpackage in java Package inside the package is called the subpackage. It should be created to categorize the package further. package pack.package; class Simple{ public static void main(String args[]){ System.out.println("Hello subpackage"); } }
  翻译: