Java Inheritance and Packages Explained
Java Inheritance and Packages Explained
Inheritance: Inheriting Classes- Type of Inheritance, Polymorphism: Overloading – Over riding, Abstract
Classes - Access Modifier: Final. Package: Understanding Packages, Defining a package, Packaging up multiple
classes, Importing and Using Packages - Understanding CLASSPATH, Standard Packages, Access Protection in
Packages- Scope of Variable: Access specifiers, - Using Inbuilt packages. Interfaces: Declaring Interfaces -
Implementing Interfaces - Using inbuilt interfaces.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object.
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.
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: 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.
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.
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.
class Employee{
float salary=40000;
}
public class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
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.
class Animal
{
void eat(){[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
class Animal
{
void eat(){[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog
{
void weep(){[Link]("weeping...");}
}
class TestInheritance2
{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
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(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Example 1:
// Java program to illustrate the
// concept of inheritance
// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// derived class
class MountainBike extends Bicycle {
// driver class
public class Test {
public static void main(String args[])
{
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
[Link]();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the
Car class
[Link]([Link] + " " + [Link]);
}
}
final Keyword
If you don't want other classes to inherit from a class, use the final keyword:
final class Vehicle {
...
}
O/P : Error
class Main {
public static void main(String[] args) {
[Link]();
}
}
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
[Link] = newName;
}
}
// Outputs "John"
Exercise
/**
* The Circle class models a circle with a radius and color.
*/
public class Circle { // Save as "[Link]"
// Constructors (overloaded)
/** Constructs a Circle instance with default value for radius and color */
/** Constructs a Circle instance with the given radius and default color */
public Circle(double r) { // 2nd constructor
radius = r;
color = "red";
}
// 3rd constructor to construct a new instance of Circle with the given radius and color
public Circle (double r, String c) { .......}
Overriding
@Override
public String toString() { // in Cylinder class
return "Cylinder: subclass of " + [Link]() // use Circle's toString()
+ " height=" + height;
}
Exercise 2:
Overriding
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to
provide a specific implementation of a method that is already provided by one of its super-classes or parent
classes.
When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-
type) as a method in its super-class, then the method in the subclass is said to override the method in the super-
class.
Method overriding is one of the way by which java achieve Run Time Polymorphism.
The version of a method that is executed will be determined by the object that is used to invoke it. If an object of
a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object
of the subclass is used to invoke the method, then the version in the child class will be executed.
In other words, it is the type of the object being referred to (not the type of the reference variable) that
determines which version of an overridden method will be executed.
// A Simple Java program to demonstrate
// method overriding in java
// Base Class
class Parent {
void show()
{
[Link]("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show()
{
[Link]("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
[Link]();
Parent/child obj2 = new Child();
[Link]();
}
}
Output:
Parent's show()
Child's show()
class Parent {
// private methods are not overridden
private void m1()
{
[Link]("From parent m1()");
}
// overriding method
// with more accessibility
@Override
public void m2()
{
[Link]("From child m2()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2();
}
}
Final methods cannot be overridden : If we don’t want a method to be overridden, we declare it as final.
// A Java program to demonstrate that
// final methods cannot be overridden
class Parent {
// Can't be overridden
final void show() {}
}
Static methods cannot be overridden (Method Overriding vs Method Hiding) : When you define a static
method with same signature as a static method in base class, it is known as method hiding.
Private methods cannot be overridden
The overriding method must have same return type
// Base Class
class Parent {
void show()
{
[Link]("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show()
{
[Link]();
[Link]("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
Parent obj = new Child();
[Link]();
}
}
Overriding and constructor : We cannot override constructor as parent and child class can never have
constructor with same name(Constructor name must always be same as Class name
class Shape
{
void draw()
{
[Link]("Inside the method of Parent class ");
[Link]("Drawing Shapes");
}
}
//Derived class
class Circle extends Shape
{
//Overriding method of base class with different implementation
@Override
void draw()
{
[Link]("Inside the overridden method of the child class ");
[Link]("Drawing Circle");
}
}
//Driver class
public class MethodOverridingDemo
{
public static void main(String args[])
{
//creating object of Base class Shape
// If a Parent type reference refers
// to a Parent object, then Parent's draw() method is called
Shape obj = new Shape();
[Link]();
// If a Parent type reference refers to a Child object Child's draw() method is called.
//This is called RUN TIME POLYMORPHISM.
Shape obj1=new Circle();
[Link]();
}
}
Exercise 2
// Base Class
class Employee {
public static int base = 10000;
int salary()
{
return base;
}
}
// Inherited class
class Manager extends Employee {
// This method overrides salary() of Parent
int salary()
{
return base + 20000;
}
}
// Inherited class
class Clerk extends Employee {
// This method overrides salary() of Parent
int salary()
{
return base + 10000;
}
}
// Driver class
class Main {
// This method can be used to print the salary of
// any type of employee using base class reference
static void printSalary(Employee e)
{
[Link]([Link]());
}
This allows us to have more than one method having the same name, if the parameters of methods are different
in number, sequence and data types of parameters
Example 1:
class DisplayOverloading
{
public void disp(char c)
{
[Link](c);
}
public void disp(char c, int num)
{
[Link](c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
[Link]('a');
[Link]('a',10);
}
}
Output:
a
a 10
Example 2:
Overloading – Difference in data type of parameters
In this example, method disp() is overloaded based on the data type of parameters – We have two methods with
the name disp(), one with parameter of char type and another method with the parameter of int type.
class DisplayOverloading2
{
public void disp(char c)
{
[Link](c);
}
public void disp(int c)
{
[Link](c );
}
}
class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
[Link]('a');
[Link](5);
}
}
Output:
a
5
Example3: Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of parameters – Both the methods have
different sequence of data type in argument list. First method is having argument list as (char, int) and second is
having (int, char). Since the sequence is different, the method can be overloaded without any issues.
class DisplayOverloading3
{
public void disp(char c, int num)
{
[Link]("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
[Link]("I’m the second definition of method disp" );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
[Link]('x', 51 );
[Link](52, 'y');
}
}
Output:
I’m the first definition of method disp
I’m the second definition of method disp
Polymorphism
Polymorphism is one of the OOPs features that allows us to perform a single action in different ways.
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
}
}
Output
30
60
Runtime Polymorphism (or Dynamic polymorphism)
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an
overridden method is resolved at runtime
In this process, an overridden method is called through the reference variable of a superclass. The determination
of the method to be called is based on the object being referred to by the reference variable
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
class A{}
class B extends A{}
A a=new B();//upcasting
class Bike{
void run(){[Link]("running");}
}
class Splendor extends Bike{
void run(){[Link]("running safely with 60km");}
Output:
running safely with 60km.
Example
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();
[Link]("SBI Rate of Interest: "+[Link]());
b=new ICICI();
[Link]("ICICI Rate of Interest: "+[Link]());
b=new AXIS();
[Link]("AXIS Rate of Interest: "+[Link]());
}
}
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Example:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
}
class Cat extends Animal{
void eat(){[Link]("eating rat...");}
}
class Lion extends Animal{
void eat(){[Link]("eating meat...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal a;
a=new Dog();
[Link]();
a=new Cat();
[Link]();
a=new Lion();
[Link]();
}}
90
Java Runtime Polymorphism with Multilevel Inheritance
Example
class Animal{
void eat(){[Link]("eating");}
}
class Dog extends Animal{
void eat(){[Link]("eating fruits");}
}
class BabyDog extends Dog{
void eat(){[Link]("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Example
class Animal{
void eat(){[Link]("animal is eating...");}
}
class Dog extends Animal{
void eat(){[Link]("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
[Link]();
}}
Output:
Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
Using Super
Super Variable
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}
void display()
{
/* print maxSpeed of base class (vehicle) */
[Link]("Maximum Speed: " + [Link]);
}
}
Super Method
/* Subclass Student */
class Student extends Person
{
void message()
{
[Link]("This is student class");
}
Super Constructor
/* superclass Person */
class Person
{
Person()
{
[Link]("base class");
}
Person(int s)
{
//super(1);
[Link]("Student class Constructor");
}
Student(int s)
{
super(5);
[Link](s);
}
}
Example 1:
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
[Link]("Zzz");
}
}
class Main {
public static void main(String[] args) {
Cat myCat = new Cat(); // Create a Cat object
[Link]();
[Link]();
}
}
Example 2:
abstract class Base {
abstract void fun();
}
class Derived extends Base {
void fun()
{
[Link]("Derived fun() called");
}
}
class Main {
public static void main(String args[])
{
// Uncommenting the following line will cause
// compiler error as the line tries to create an
// instance of abstract class. Base b = new Base();
we can have an abstract class without any abstract method. This allows us to create classes that cannot
be instantiated but can only be inherited
class Main {
public static void main(String args[])
{
Derived d = new Derived();
[Link]();
}
}
Abstract classes can also have final methods (methods that cannot be overridden)
class Main {
public static void main(String args[])
{
Base b = new Derived();
[Link]();
}
}
Output
Derived fun() called
For any abstract java class we are not allowed to create an object i.e., for abstract class instantiation is not
possible.
Similar to the interface we can define static methods in an abstract class that can be called independently
without an object.
Package: Understanding Packages, Defining a package, Packaging up multiple classes, Importing and
Using Packages - Understanding CLASSPATH, Standard Packages, Access Protection in Packages
A package is a namespace that organizes a set of related classes and interfaces. A package in Java is used to
group related classes. Think of it as a folder in a file directory. Use packages to avoid name conflicts, and to
write a better maintainable code. Packages are divided into two categories:
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
Built-in Packages
• The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
• The library contains components for managing input, database programming, and much more.
• The library is divided into packages and classes. Meaning you can either import a single or a whole
package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
import [Link]; // Import a single class
import packagename.*; // Import the whole package
Import a Class
for example, the Scanner class, which is used to get user input, write the following code:
Example
import [Link];
[Link] is a package, while Scanner is a class of the [Link] package.
Import a Package
To import a whole package, end the sentence with an asterisk sign (*).
import [Link].*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store them. Just
like folders on your computer
Example
└── root
└── mypack
└── [Link]
package mypack;
class MyPackageClass {
public static void main(String[] args) {
[Link]("This is my package!");
}
}
javac -d directory javafilename
The -d keyword specifies the destination for where to save the class file. You can use any directory name, like
c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".",
like in the example above.
When we compiled the package in the example above, a new folder was created, called "mypack".
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
Example 1:
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*; or import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
Example 2:
[Link]
package package_one;
public class ClassOne {
public void methodClassOne() {
[Link]("Hello there its ClassOne");
}
}
[Link]
package package_two;
public class ClassTwo {
public void methodClassTwo(){
[Link]("Hello there i am ClassTwo");
}
}
import package_two.ClassTwo;
import package_one.ClassOne;
[Link]
public class Testing {
public static void main(String[] args){
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
[Link]();
[Link]();
}
}
Output:
Hello there i am ClassTwo
Hello there its ClassOne
Example 3:
package letmecalculate;
public class Calculator {
public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
[Link]([Link](10, 20));
}
}
import [Link];
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
[Link]([Link](100, 200));
}
}
Creating multiple classes in a package:
In java, one program can have only one public class. If at all, there are more non-public classes in a same
program, they will not become the members of a package. But, to have multiple classes in a single package, the
directory is going to be same; while the classes are to be written in different programs.
The following example shows step-by-step approach to create a package with multiple classes.
package arithmetic;
public class Sum
{
public int add(int x,int y)
{
return x+y;
}
}
Create the second file (file name should be [Link]) and compile the file in the same directory.
package arithmetic;
public class Difference
{
public int sub(int x,int y)
{
return x-y;
}
}
Now, Move to parent (working) directory, write the following file ([Link]) and execute it.
import arithmetic.*;
class Test
{
public static void main(String as[])
{
Sum s1 = new Sum();
[Link]([Link](8,5)); // prints 13
Difference d1 = new Difference ();
[Link]([Link](8,5)); // prints 3
}
}
CLASSPATH - For Locating Classes:
CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the
processes) needed for the Java compiler and runtime to locate the Java packages/classes used in a Java program.
import [Link]
It makes the Menu class available in the package [Link] to our current class. Such that when we call
The JVM knows where to find the class Menu. Now, how will the JVM know this location? It is impractical for
it to go through every folder on your system and search for it. Thus, using the CLASSPATH variable we provide
it the place where we want it to look. We put directories and jars in the CLASSPATH variable.
Let’s say the above package resides in the directory dir. The complete path of the Menu class file would be
dir/org/company/Menu. We’ll specify only the directory dir in our classpath variable, as rest information
regarding the path is provided by the import statements
Setting CLASSPATH:
CLASSPATH can be set by any of the following ways:
• CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ?
Advanced ? Environment Variables ? choose “System Variables” (for all the users) or “User Variables”
(only the currently login user) ? choose “Edit” (if CLASSPATH already exists) or “New” ? Enter
“CLASSPATH” as the variable name ? Enter the required directories and JAR files (separated by
semicolons) as the value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\[Link]”). Take note that you
need to include the current working directory (denoted by ‘.’) in the CLASSPATH
• CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following
command:
SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\[Link]
• Instead of using the CLASSPATH environment variable, you can also use the command-line option -
classpath or -cp of the javac and java commands, for example,
Built-in Packages
These packages consist of a large number of classes which are a part of Java [Link] of the commonly used
built-in packages are:
1) [Link]: Contains language support classes(e.g classed which defines primitive data types, math operations).
This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.
3) [Link]: Contains utility classes which implement data structures like Linked List, Dictionary and support ;
for Date / Time operations.
4) [Link]: Contains classes for creating Applets.
5) [Link]: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) [Link]: Contain classes for supporting networking operations.
The program below shows how to use the Math class of [Link] package which provides many different
methods for different mathematical operations.
class JavaLangExample {
public static void main(String args []) {
int a = 20, b =30;
int sum = [Link](a,b);
int max = [Link](a,b);
double pi = [Link];
[Link]("Sum = "+sum+", Max = "+max+", PI = "+pi);
}
}
Java io package([Link])
Java IO(Input/Output) package provides classes and interfaces for handling system(computer, laptop etc) input
and output operations. Using these classes programmer can take the input from user and do operations on that
and then display the output to user. Generally input is given using keyboard/keypad. We can also do file
handling(read/write) using the classes of this package.
The program below uses the Console class of [Link] package to take the input from user and then print that
input to user's screen(command prompt or any other terminal used).
import [Link];
class JavaIOExample {
public static void main(String args []) {
Console cs = [Link]();
[Link]("Enter your name : ");
String name = [Link]();
[Link]("Welcome : "+name);
}
}
class JavaUtilExample {
public static void main(String args []) {
int[] intArray = {10,30,20,50,40};
[Link](intArray);
[Link]("Sorted array : %s", [Link](intArray));
}
}
[Link]
The [Link] class contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.
[Link] class
Introduction
The [Link] class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this [Link] are constant, their values cannot be changed after they are created
boolean contains(CharSequence s)
This method ceturns true if and only if this string contains the specified sequence of char values.
int hashCode()
This method returns a hash code for this string.
boolean isEmpty()
This method returns true if, and only if, length() is 0.
int length()
This method returns the length of this string.
char[] toCharArray()
This method converts this string to a new character array.
String toLowerCase()
This method converts all of the characters in this String to lower case using the rules of the default locale.
String toString()
This method returns the string itself.
String toUpperCase()
This method converts all of the characters in this String to upper case using the rules of the default locale.
String trim()
This method returns a copy of the string, with leading and trailing whitespace omitted.
A package defined inside another package is known as sub package. Sub packages are nothing different than
packages except that they are defined inside another packages. Sub packages are similar as sub directories which
is a directory created inside another directory.
package [Link];
class MySubPackageProgram {
public static void main(String args []) {
[Link]("My sub package program");
}
}
here the package name is [Link] which is a subpackage
javac mypack\testpack\[Link]
java [Link]
For example importing package mypack in your program will not import the classes of sub package testpack
given above. Importing sub packages is same as importing packages. The syntax of importing a sub package is :
Example
import [Link].*;
import [Link];
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
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(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:
class A{
private A(){}//private constructor
void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
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.
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.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
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.
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.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output:Hello
Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers
are lexically (or statically) scoped, [Link] of a variable can determined at compile time and independent of
function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be
covered under following categories.
class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}
The above code uses this keyword to differentiate between the local and class variables.
Output
Test.x: 22
t.x: 22
t.y: 33
y: 44
// [Link](x);
}
}
Example
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
[Link](x);
}
Right Program
[Link](x);
}
}
Example
class Test
{
public static void main(String args[])
{
int a = 5;
for (int a = 0; a < 5; a++)
{
[Link](a);
}
}
}
Output:
error: variable a is already defined in method main(String[])
Example
inner loop will terminate before the outer loop variable is declared. So the inner loop variable is
destroyed first and then the new variable of same name has been created
class Test {
public static void main(String args[])
{
for (int i = 1; i <= 10; i++) {
[Link](i);
}
int i = 20;
[Link](i);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
20
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and 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.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
Example
In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by someone else.
The implementation part is hidden by the user who uses the interface.
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){[Link]("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
[Link]();
}}
Example
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}}
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 Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
interface Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
// to decrease speed
@Override
public void applyBrakes(int decrement){
}
class GFG {
Another feature that was added in JDK 8 is that we can now define static methods in interfaces which can be
called independently without an object. Note: these methods are not inherited
In-Built Interface
Java contains a set of functional interfaces designed for commonly occuring use cases, so you don't have to create
your own functional interfaces for every little use case. In the following sections I will be describing some of these
built-in functional interfaces in Java.
Function
The Java Function interface ([Link]) interface is one of the most central functional interfaces in
Java. The Function interface represents a function (method) that takes a single parameter and returns a single value.
Here is how the Function interface definition looks:
The only method you have to implement to implement the Function interface is the apply() method. Here is
a Function implementation example:
@Override
public Long apply(Long aLong) {
return aLong + 3;
}
}
This Function implementation implements the apply() method so it takes a Long as parameter, and returns a Long.
Here is an example of using the above AddThree class:
First this example creates a new AddThree instance and assigns it to a Function variable. Second, the example calls
the apply() method on the AddThree instance. Third, the example prints out the result (which is 7).
You can also implement the Function interface using a Java lambda expression. Here is how that looks:
As you can see, the Function interface implementation is now inlined in the declaration of
the adderLambda variable, rather than in a separate class. This is a bit shorter, plus we can see directly in the above
code what it is doing.
Predicate
The Java Predicate interface, [Link], represents a simple function that takes a single value as
parameter, and returns true or false. Here is how the Predicate functional interface definition looks:
The Predicate interface contains more methods than the test() method, but the rest of the methods are default or
static methods which you don't have to implement.
You can implement the Predicate interface using a class, like this:
This lambda implementation of the Predicate interface effectively does the same as the implementation above that
uses a class.
Supplier
The Java Supplier interface is a functional interface that represents an function that supplies a value of some sorts.
The Supplier interface can also be thought of as a factory interface. Here is an example implementation of the
Java Supplier interface:
This Java Supplier implementation returns a new Integer instance with a random value between 0 and 1000.
Consumer
The Java Consumer interface is a functional interface that represents an function that consumes a value without
returning any value. A Java Consumer implementation could be printing out a value, or writing it to a file, or over
the network etc. Here is an example implementation of the Java Consumer interface:
This Java Consumer implementation prints the value passed as parameter to it out to [Link].
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
[Link](5);
[Link](9);
[Link](8);
[Link](1);
Consumer<Integer> method = (n) -> { [Link](n+2); };
[Link]( method );
}
}
Output:
7
11
10
3