0% found this document useful (0 votes)
9 views53 pages

Java Inheritance and Packages Explained

This document covers the concepts of inheritance and packages in Java, detailing types of inheritance such as single, multilevel, and hierarchical, along with examples. It explains the use of access modifiers, the final keyword, and method overriding, emphasizing the importance of reusability and polymorphism in object-oriented programming. Additionally, it includes code snippets to illustrate these concepts effectively.

Uploaded by

aizenw123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views53 pages

Java Inheritance and Packages Explained

This document covers the concepts of inheritance and packages in Java, detailing types of inheritance such as single, multilevel, and hierarchical, along with examples. It explains the use of access modifiers, the final keyword, and method overriding, emphasizing the importance of reusability and polymorphism in object-oriented programming. Additionally, it includes code snippets to illustrate these concepts effectively.

Uploaded by

aizenw123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT II INHERITANCE AND PACKAGES 9

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.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).


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: 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 syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

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]);
}
}

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. Multiple inheritance is
not supported in Java through class.

Java doesn't support multiple inheritance


Java doesn't support Hybrid Inheritance

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single inheritance.

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]();
}
}

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.

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]();
}
}

Hierarchical Inheritance Example

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;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
[Link] = gear;
[Link] = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}

// derived class
class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear, int speed,int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override public String toString()
{
return ([Link]() + "\nseat height is "
+ seatHeight);
}
}

// driver class
public class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


[Link]([Link]());
}
}
Example 2:

class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// 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 {
...
}

class Car extends Vehicle {


...
}

O/P : Error

protected Members in Inheritance


In Java, if a class includes protected fields and methods, then these fields and methods are accessible from the
subclass of the class.
class Animal {
protected String name;

protected void display() {


[Link]("I am an animal.");
}
}

class Dog extends Animal {

public void getInfo() {


[Link]("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access protected field and method


// using the object of subclass
[Link] = "Rocky";
[Link]();

[Link]();
}
}

Example for Get and Set

public class Person {


private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
[Link] = newName;
}
}

public class Main {


public static void main(String[] args) {
Person myObj = new Person();
[Link]("John"); // Set the value of the name variable to "John"
[Link]([Link]());
}
}

// Outputs "John"

Exercise
/**
* The Circle class models a circle with a radius and color.
*/
public class Circle { // Save as "[Link]"

private double radius;


private String color;

// Constructors (overloaded)
/** Constructs a Circle instance with default value for radius and color */

public Circle() { // 1st (default) constructor


radius = 1.0;
color = "red";
}

/** 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) { .......}

/** Returns the radius */


public double getRadius() {
return radius;
}

// Getter for instance variable color


public String getColor() { ....... }
// Setter for instance variable color

public double getArea() {


return radius*radius*[Link];
}
// Setter for instance variable radius
public void setRadius(double radius) {
this. radius = radius;
}

// Setter for instance variable color


public void setColor(String newColor) { ....... }
}

/** Return a self-descriptive string of this instance in the form of Circle[radius=?,color=?] */


public String toString() {
return "Circle[radius=" + radius + " color=" + color + "]";
}

public class Cylinder extends Circle { // Save as "[Link]"


private double height; // private variable

// Constructor with default color, radius and height


public Cylinder() {
super(); // call superclass no-arg constructor Circle()
height = 1.0;
}
// Constructor with default radius, color but given height
public Cylinder(double height) {
super(); // call superclass no-arg constructor Circle()
[Link] = height;
}
// Constructor with default color, but given radius, height
public Cylinder(double radius, double height) {
super(radius); // call superclass constructor Circle(r)
[Link] = height;
}

// A public method for retrieving the height


public double getHeight() {
return height;
}

// A public method for computing the volume of cylinder


// use superclass method getArea() to get the base area
public double getVolume() {
return getArea()*height;
}
}

public class TestCylinder { // save as "[Link]"


public static void main (String[] args) {
// Declare and allocate a new instance of cylinder
// with default color, radius, and height
Cylinder c1 = new Cylinder();
[Link]("Cylinder:"
+ " radius=" + [Link]()
+ " height=" + [Link]()
+ " base area=" + [Link]()
+ " volume=" + [Link]());

// Declare and allocate a new instance of cylinder


// specifying height, with default color and radius
Cylinder c2 = new Cylinder(10.0);
[Link]("Cylinder:"
+ " radius=" + [Link]()
+ " height=" + [Link]()
+ " base area=" + [Link]()
+ " volume=" + [Link]());

// Declare and allocate a new instance of cylinder


// specifying radius and height, with default color
Cylinder c3 = new Cylinder(2.0, 10.0);
[Link]("Cylinder:"
+ " radius=" + [Link]()
+ " height=" + [Link]()
+ " base area=" + [Link]()
+ " volume=" + [Link]());
}
}

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()

Rules for method overriding:


Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less,
access than the overridden method. For example, a protected instance method in the super-class can be made
public, but not private, in the subclass. Doing so, will generate compile-time error.

// A Simple Java program to demonstrate


// Overriding and Access-Modifiers

class Parent {
// private methods are not overridden
private void m1()
{
[Link]("From parent m1()");
}

protected void m2()


{
[Link]("From parent m2()");
}
}

class Child extends Parent {


// new m1() method
// unique to Child class
private void m1()
{
[Link]("From child 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() {}
}

class Child extends Parent {


// This would produce error
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

Invoking overridden method from sub-class

// A Java program to demonstrate that overridden


// method can be called from sub-class

// 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

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).
4. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the
overridden method of parent class.
5. We cannot override the method declared as final and static.

//Java Program to demonstrate the real scenario of Java Method Overriding


//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
[Link]("SBI Rate of Interest: "+[Link]());
[Link]("ICICI Rate of Interest: "+[Link]());
[Link]("AXIS Rate of Interest: "+[Link]());
}
}
Exercise

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

// A Simple Java program to demonstrate application


// of overriding in Java

// 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]());
}

public static void main(String[] args)


{
Employee obj1 = new Manager();

// We could also get type of employee using


// one more overridden [Link] getType()
[Link]("Manager's salary : ");
printSalary(obj1);

Employee obj2 = new Clerk();


[Link]("Clerk's salary : ");
printSalary(obj2);
}
}
Method Overloading

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

Three ways to overload a method


In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
add(int, int)
add(int, int, int)
2. Data type of parameters.
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
add(int, float)
add(float, int)

Invalid case of method overloading:


If two methods have same name, same parameters and have different return type, then this is not a valid method
overloading example. This will throw compilation error.

int add(int, int)


float add(int, int)

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.

There are two types of polymorphism in java:


1) Static Polymorphism also known as compile time polymorphism
2) Dynamic Polymorphism also known as runtime polymorphism

Compile time Polymorphism (or Static polymorphism)


Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading is an
example of compile time polymorphism.

Example of static Polymorphism


Method overloading is one of the way java supports static polymorphism. Here we have two definitions of the
same method add() which add method would be called is determined by the parameter list at the compile time.
That is the reason this is also known as compile time polymorphism.

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

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides
its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class Bike{
void run(){[Link]("running");}
}
class Splendor extends Bike{
void run(){[Link]("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
[Link]();
}
}

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]();
}}

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a data member speedlimit. We are accessing the data member
by the reference variable of Parent class which refers to the subclass object. Since we are accessing the data
member which is not overridden, hence it will access the data member of the Parent class always.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
[Link]([Link]);//90
}
Output:

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;
}

/* sub class Car extending vehicle */


class Car extends Vehicle
{
int maxSpeed = 180;

void display()
{
/* print maxSpeed of base class (vehicle) */
[Link]("Maximum Speed: " + [Link]);
}
}

/* Driver program to test */


class Supervar
{
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}

Super Method

/* Base class Person */


class Person
{
void message()
{
[Link]("This is person class");
}
}

/* Subclass Student */
class Student extends Person
{
void message()
{
[Link]("This is student class");
}

// Note that display() is only in Student class


void display()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method


[Link]();
}
}
/* Driver program to test */
class Supermet
{
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


[Link]();
}
}

Super Constructor
/* superclass Person */
class Person

{
Person()
{
[Link]("base class");
}

Person(int s)
{

[Link]("Person class Constructor");


}
}

/* subclass Student extending the Person class */


class Student extends Person
{
Student()
{
// invoke or call parent class constructor

//super(1);
[Link]("Student class Constructor");

}
Student(int s)
{
super(5);
[Link](s);
}
}

/* Driver program to test*/


class Supercon
{
public static void main(String[] args)
{
Student s = new Student(5);
}
}
Abstract Class

Abstract Classes and Methods


Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the
subclass (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal {


public abstract void animalSound();
public void sleep() {
[Link]("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class:

Animal myObj = new Animal(); // will generate an error


To access the abstract class, it must be inherited from another class

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");
}
}

// Subclass (inherit from Animal)


class Cat extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The cat says: Meow");
}
}

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 references of Base type.


Base b = new Derived();
[Link]();
}
}
an abstract class can contain constructors in Java. And a constructor of abstract class is called when an
instance of an inherited class is created

// An abstract class with constructor


abstract class Base {
Base()
{
[Link]("Base Constructor Called");
}
abstract void fun();
}
class Derived extends Base {
Derived()
{
[Link]("Derived Constructor Called");
}
void fun()
{
[Link]("Derived fun() called");
}
}
class Main {
public static void main(String args[])
{
Derived d = new Derived();
}
}
Output
Base Constructor Called
Derived Constructor Called

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

// An abstract class without any abstract method


abstract class Base {
void fun() { [Link]("Base fun() called"); }
}

class Derived extends Base {


}

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)

// An abstract class with a final method


abstract class Base {
final void fun()
{
[Link]("Derived fun() called");
}
}

class Derived extends Base {


}

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.

// An abstract class example


abstract class Test {
public static void main(String args[])
{
// Try to create an object
Test t = new Test();
}
}
Output:

Compile time error. Test is abstract;


cannot be instantiated Test t=new Test();

Similar to the interface we can define static methods in an abstract class that can be called independently
without an object.

abstract class Party {


static void doParty()
{
[Link]("Lets have some fun!!");
}
}

public class Main extends Party {


public static void main(String[] args)
{
[Link]();
}
}
Output
Lets have some fun!!

Package: Understanding Packages, Defining a package, Packaging up multiple classes, Importing and
Using Packages - Understanding CLASSPATH, Standard Packages, Access Protection in Packages

Java Packages & API

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:

Built-in Packages (packages from the Java API)


User-defined Packages (create your own packages)

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

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]

To create a package, use the package keyword

package mypack;
class MyPackageClass {
public static void main(String[] args) {
[Link]("This is my package!");
}
}
javac -d directory javafilename

C:\Users\Your Name>javac -d . [Link]

This forces the compiler to create the "mypack" package.

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".

To run the [Link] file, write the following:

C:\Users\Your Name>java [Link]

How to access package from another package?

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

fully qualified name


//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}

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.

· First create a directory by name “Arithmetic” and move to that directory


· Create the following file (file name should be [Link]) and compile the file in the same directory.

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

Menu menu = new Menu()

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,

java –classpath c:\javaproject\classes [Link].project1.subproject2.MyClass3

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.

Java lang package([Link])


This packages contains the fundamental or core classes of java language without which it won't be possible to
write program in java. This package is automatically imported to each program, which means we can use the
classes of this package directly in our program.

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);
}
}

Java util package([Link])


Java util package provides the basic utility classes to java programmers. It is one of the most useful package for
java programmers, it helps them to achieve different types of requirements easily by using it's predefined
classes.

Java program of demonstrating use of [Link] package


import [Link];

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.

Method & Description

static double abs(double a)


This method returns the absolute value of a double value.

static float abs(float a)


This method returns the absolute value of a float value.

static int abs(int a)


This method returns the absolute value of an int value.

static long abs(long a)


This method returns the absolute value of a long value.

static double acos(double a)


This method returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.

static double asin(double a)


This method returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.

static double atan(double a)


This method returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2.

static double atan2(double y, double x)


This method returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates
(r, theta).
static double cbrt(double a)
This method returns the cube root of a double value.

static double ceil(double a)


This method returns the smallest (closest to negative infinity) double value that is greater than or equal to the
argument and is equal to a mathematical integer.

static double cos(double a)


This method returns the trigonometric cosine of an angle.

static double cosh(double x)


This method returns the hyperbolic cosine of a double value.

static double exp(double a)


This method returns Euler's number e raised to the power of a double value.

static double floor(double a)


This method returns the largest (closest to positive infinity) double value that is less than or equal to the
argument and is equal to a mathematical integer.

static double log(double a)


This method returns the natural logarithm (base e) of a double value.

static double max(double a, double b)


This method returns the greater of two double values.

static float max(float a, float b)


This method returns the greater of two float values.

static int max(int a, int b)


This method returns the greater of two int values.

static long max(long a, long b)


This method returns the greater of two long values.

static double min(double a, double b)


This method returns the smaller of two double values.

static float min(float a, float b)


This method returns the smaller of two float values.

static int min(int a, int b)


This method returns the smaller of two int values.

static long min(long a, long b)


This method returns the smaller of two long values.

static double pow(double a, double b)


This method returns the value of the first argument raised to the power of the second argument.

static double random()


This method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

static long round(double a)


This method returns the closest long to the argument.

static int round(float a)


This method returns the closest int to the argument.

static double sin(double a)


This method returns the hyperbolic sine of a double value.

static double sinh(double x)


This method Returns the hyperbolic sine of a double value.

static double sqrt(double a)


This method returns the correctly rounded positive square root of a double value.

static double tan(double a)


This method returns the trigonometric tangent of an angle.r

static double tanh(double x)


This method returns the hyperbolic tangent of a double value.

static double toDegrees(double angrad)


This method converts an angle measured in radians to an approximately equivalent angle measured in degrees.

static double toRadians(double angdeg)


This method converts an angle measured in degrees to an approximately equivalent angle measured in radians.

[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

Method & Description

char charAt(int index)


This method returns the char value at the specified index.

int compareTo(String anotherString)


This method compares two strings lexicographically.

int compareToIgnoreCase(String str)


This method compares two strings lexicographically, ignoring case differences.

String concat(String str)


This method concatenates the specified string to the end of this string.

boolean contains(CharSequence s)
This method ceturns true if and only if this string contains the specified sequence of char values.

boolean contentEquals(CharSequence cs)


This method compares this string to the specified CharSequence.

boolean contentEquals(StringBuffer sb)


This method compares this string to the specified StringBuffer.

boolean endsWith(String suffix)


This method tests if this string ends with the specified suffix.

boolean equals(Object anObject)


This method compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)


This method compares this String to another String, ignoring case considerations.

static String format(Locale l, String format, Object... args)


This method returns a formatted string using the specified locale, format string, and arguments.

static String format(String format, Object... args)


This method returns a formatted string using the specified format string and arguments.

int hashCode()
This method returns a hash code for this string.

int indexOf(int ch)


This method returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)


This method returns the index within this string of the first occurrence of the specified character, starting the
search at the specified index.

int indexOf(String str)


This method returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)


This method returns the index within this string of the first occurrence of the specified substring, starting at
the specified index.

boolean isEmpty()
This method returns true if, and only if, length() is 0.

int lastIndexOf(int ch)


This method returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)


This method returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.

int lastIndexOf(String str)


This method returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)


This method returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index.

int length()
This method returns the length of this string.

boolean matches(String regex)


This method tells whether or not this string matches the given regular expression.

String replace(char oldChar, char newChar)


This method returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.

String replace(CharSequence target, CharSequence replacement)


This method replaces each substring of this string that matches the literal target sequence with the specified
literal replacement sequence.

String replaceAll(String regex, String replacement)


This method replaces each substring of this string that matches the given regular expression with the given
replacement.

String replaceFirst(String regex, String replacement)


This method replaces the first substring of this string that matches the given regular expression with the given
replacement.

String[] split(String regex)


This method splits this string around matches of the given regular expression.

String[] split(String regex, int limit)


This method splits this string around matches of the given regular expression.

boolean startsWith(String prefix)


This method tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)


This method tests if the substring of this string beginning at the specified index starts with the specified prefix.

CharSequence subSequence(int beginIndex, int endIndex)


This method returns a new character sequence that is a subsequence of this sequence.

String substring(int beginIndex)


This method returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)


This method returns a new string that is a substring 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 toLowerCase(Locale locale)


This method converts all of the characters in this String to lower case using the rules of the given 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 toUpperCase(Locale locale)


This method converts all of the characters in this String to upper case using the rules of the given Locale.

String trim()
This method returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(boolean b)


This method returns the string representation of the boolean argument.

static String valueOf(char c)


This method returns the string representation of the char argument.

static String valueOf(char[] data)


This method returns the string representation of the char array argument.

static String valueOf(char[] data, int offset, int count)


This method Returns the string representation of a specific subarray of the char array argument.

static String valueOf(double d)


This method returns the string representation of the double argument.

static String valueOf(float f)


This method returns the string representation of the float argument.

static String valueOf(int i)


This method returns the string representation of the int argument.

static String valueOf(long l)


This method returns the string representation of the long argument.

static String valueOf(Object obj)


This method returns the string representation of the Object argument.

Sub Packages in Java

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]

Why do we create Sub Packages


Subpackages are created to categorize/divide a package further. It's similar as creating sub folder inside a folder
to categorize it further so that you can organize your content more better which will make easy to access the
content. A package may have many sub packages inside it
How to import Sub packages
To access the classes or interfaces of a sub package, you need to import the sub package in your program first.
Importing the parent package of a sub package doesn't import the sub packages classes or interfaces in your
program. They must be imported explicitly in your program to access their classes and interfaces.

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 :

// To import all classes of a sub package


import [Link].*;
// To import specific class of a sub package
import [Link];

Example

import [Link].*;
import [Link];

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here,
we are going to learn the access modifiers only.

Access within within outside package by subclass outside


Modifier class package only package

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

Java Access Modifiers with Method Overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
class A{
protected void msg(){[Link]("Hello java");}
}
public class Simple extends A{
void msg(){[Link]("Hello java");}//[Link]
public static void main(String args[]){
Simple obj=new Simple();
[Link]();
}
}
The default modifier is more restrictive than protected. That is why, there is a compile-time error.

Scope of Variables In Java

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.

Member Variables (Class Level Scope)


These variables must be declared inside class (outside any function). They can be directly accessed anywhere in
class
public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {... }
int method2() {. ..}
char c;
}

Local Variables (Method Level Scope)


Variables declared inside a method have method level scope and can’t be accessed outside the method.
public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}
Local variables don’t exist after method’s execution is over.

The variable got passed in as a parameter to the method:

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.

public class Test


{
static int x = 11;
private int y = 33;
public void method1(int x)
{
Test t = new Test();
this.x = 22;
y = 44;

[Link]("Test.x: " + Test.x);


[Link]("t.x: " + t.x);
[Link]("t.y: " + t.y);
[Link]("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}

Output
Test.x: 22
t.x: 22
t.y: 33
y: 44

Loop Variables (Block Scope)


A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only.
public class Test
{
public static void main(String args[])
{
{
// The variable x has scope within
// brackets
int x = 10;
[Link](x);
}

// Uncommenting below line would produce


// error since variable x is out of scope.

// [Link](x);
}
}

Example

class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
[Link](x);
}

// Will produce error


[Link](x);
}
}

Right Program

// Above program after correcting the error


class Test
{
public static void main(String args[])
{
int x;
for (x = 0; x < 4; x++)
{
[Link](x);
}

[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.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

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.
}

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are public and abstract.

The relationship between classes and interfaces


a class extends another class, an interface extends another interface, but a class implements an interface.

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");}

public static void main(String args[]){


A7 obj = new A7();
[Link]();
[Link]();
}
}
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
[Link]();
[Link]();
}
}
Example
import [Link].*;

interface Vehicle {

// all are the abstract methods.


void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bicycle implements 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){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}

public void printStates() {


[Link]("speed: " + speed
+ " gear: " + gear);
}
}

class Bike implements 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){

speed = speed + increment;


}

// to decrease speed
@Override
public void applyBrakes(int decrement){

speed = speed - decrement;


}

public void printStates() {


[Link]("speed: " + speed
+ " gear: " + gear);
}

}
class GFG {

public static void main (String[] args) {

// creating an inatance of Bicycle


// doing some operations
Bicycle bicycle = new Bicycle();
[Link](2);
[Link](3);
[Link](1);

[Link]("Bicycle present state :");


[Link]();

// creating instance of the bike.


Bike bike = new Bike();
[Link](1);
[Link](4);
[Link](3);

[Link]("Bike present state :");


[Link]();
}
}

New features added in interfaces in JDK 8


Prior to JDK 8, interface could not define implementation. We can now add default implementation for
interface methods
// An example to show that interfaces can
// have methods from JDK 1.8 onwards
interface In1
{
final int a = 10;
default void display()
{
[Link]("hello");
}
}

// A class that implements the interface.


class TestClass implements In1
{
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
[Link]();
}
}

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

// An example to show that interfaces can


// have methods from JDK 1.8 onwards
interface In1
{
final int a = 10;
static void display()
{
[Link]("hello");
}
}

// A class that implements the interface.


class TestClass implements In1
{
// Driver Code
public static void main (String[] args)
{
[Link]();
}
}

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:

public interface Function<T,R> {

public <R> apply(T parameter);


}
The Function interface actually contains a few extra methods in addition to the methods listed above, but since they
all come with a default implementation, you do not have to implement these extra methods. The extra methods will
be explained in later sections.

The only method you have to implement to implement the Function interface is the apply() method. Here is
a Function implementation example:

public class AddThree implements Function<Long, Long> {

@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:

Function<Long, Long> adder = new AddThree();


Long result = [Link]((long) 4);
[Link]("result = " + result);

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:

Function<Long, Long> adder = (value) -> value + 3;


Long resultLambda = [Link]((long) 8);
[Link]("resultLambda = " + resultLambda);

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:

public interface Predicate<T> {


boolean test(T t);
}

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:

public class CheckForNull implements Predicate {


@Override
public boolean test(int x) {
return x != 0;
}
}
You can also implement the Java Predicate interface using a Lambda expression. Here is an example of
implementing the Predicate interface using a Java lambda expression:

Predicate p = (value) -> value != 0;


[Link]([Link](10));//True

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:

public interface Supplier<T> {


T get();
}

Supplier<Double> s = () -> [Link]();


[Link]([Link]());

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:

public interface Consumer<T> {


void accept(T t);
}

Consumer<Integer> c = (value) -> [Link](value);


[Link](10);

This Java Consumer implementation prints the value passed as parameter to it out to [Link].

Use Java's Consumer interface to store a lambda expression in a variable:

Java Lambda Expressions


Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in
parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and
they can be implemented right in the body of a method.
(parameter1, parameter2) -> expression

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

You might also like