[go: up one dir, main page]

0% found this document useful (0 votes)
4 views27 pages

Abstraction in Java

Uploaded by

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

Abstraction in Java

Uploaded by

pubggaming747474
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

CLASS, OBJECT AND METHODS

Java program is a collection of objects that communicate via invoking each other's
methods. We now briefly look into class, object, methods, and instance variables.
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports. A class is declared by use of the
class keyword. A simplified general form of a class definition is shown here:

class classname { type instance-variable1;


type instance-variable2; // …
type instance-variableN;
type methodname1(parameter-list)
{ // body of method }
type methodname2(parameter-list) { // body of method } // ...
type methodnameN(parameter-list) { // body of method }
}

The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a
class are called members of the class. In most classes, the instance variables are acted
upon and accessed by the methods defined for that class Simple Class
Class Sample
{ int len, float ht
void get() { // body }
}
Here a class Sample contains two variable len and ht Object in Java Object is the
physical as well as logical entity whereas class is the logical entity only. An object has
three characteristics:  state: represents data (value) of an object.  behavior:
represents the behavior (functionality) of an object such as deposit, withdraw etc. 
identity: Object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely. Object is an instance of a class. Class is a template or blueprint from
which objects are created. So object is the instance(result) of a class. Object
Definitions:  Object is a real world entity. Object is a run time entity.  Object is an
entity which has state and behavior.  Object is an instance of a class.
Sample s=new Sample() here s is an object for the class Sample new operator is used
to create an object
Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed. Let's create the Simple java program: 1.
class Sample{ 2. public static void main(String args[])
3. System.out.println("How are you ");
4. }
5. } save this file as Sample.java To compile: javac Sample.java
6. To execute: java Sample Java Identifiers All Java components require names.
Names used for classes, variables, and methods are called identifiers. In Java, there
are several points to remember about identifiers. They are as follows −  All
identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).  After the first character, identifiers can have any combination of
characters.  A key word cannot be used as an identifier.  Most importantly,
identifiers are case sensitive.  Examples of legal identifiers: age, $salary, _value,
__1_value.  Examples of illegal identifiers: 123abc, -salary. Java Modifiers: There
are two categories of modifiers −  Access Modifiers − default, public , protected,
private  Non-access Modifiers − final, abstract, strictfp

III DATA TYPES There are two data types available in Java −  Primitive Data
Types  Non Primitive Types

Abstraction in Java:
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only important things to the user and hides the internal
details for example sending sms, you just type the text and send the message. You
don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Definition of Abstract Class:
A class which contains the abstract keyword in its declaration is known as abstract
class.
Abstract classes may or may not contain abstract methods, i.e., methods without
body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared
abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
Example of abstract class:
abstract class A{}
Abstract method:
A method that is declared as abstract and does not have implementation is known
as
abstract method.
Example abstract method:
abstract void printStatus();
//no body and abstract
Example of abstract class that has abstract method:
In this example, Bike the abstract class that contains only one abstract method run.
It
implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println ("running safely..");Unit-2 Object and Classes
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
}
}
Output:
running safely

Inheritance in Java:
Inheritance is one of the key features of object-oriented programming because it
allows the creation of hierarchical classifications.
Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new methods and fields also.
Inheritance has advantages like:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
In the terminology of Java, a class that is inherited is called a super class. The new
class is
called a subclass.
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.
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B and C are three classes.
The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there
will
be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile
time
error if you inherit 2 classes.
So whether you have same method or different, there will be compile time error
now.
class A
{
void msg(){System.out.println("Hello");}
}
class BUnit-2 Object and Classes
{
void msg()
{
System.out.println("Welcome");
}
}
class C extends A,B
{
//suppose if it were
Public Static void main(String args[])
{
C obj=new C();
obj.msg();
//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error
Types of inheritance in java:
On the basis of class, there are following types of inheritance supported in java:
1. Single Inheritance
2. Multiple Inheritance (Through Interface)
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (Through Interface)
On the basis of class, there can be 3 types of inheritance in java: single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported through
interface
only.
1. Single Inheritance:
Single Inheritance is the simple inheritance of all, when a class extends another
class
(Only one class) then we call it as Single inheritance.
The below diagram represents the single inheritance in java where Class B extends
only one class Class A. Here Class B will be the Sub class(child class) and Class A will
be one and only Super class (parent class).Unit-2 Object and Classes
Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Output :
Base class method
Child class method
2. Multilevel Inheritance:
Multilevel inheritance is a feature of oops concept, where a class is derived from
another derived class.
As seen in the below diagram. ClassB inherits the property of ClassA and
again ClassB act as a parent for ClassC. In Short ClassA parent
for ClassB and ClassB parent for ClassC.Unit-2 Object and Classes

MultiLevel Inheritance Example


public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
ClassC c = new ClassC();
c.dispA();
c.dispB();
c.dispC();
}
}
Output :
disp() method of ClassA
disp() method of ClassB
disp() method of ClassC
3. Hierarchical Inheritance:
Hierarchical inheritance is a feature of oops concept, where more than one classes
are derived from one base class, one parent class is inherited by many sub
classes.Unit-2 Object and Classes

Hierarchical Inheritance Example


public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassDextends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
ClassB b = new ClassB();
b.dispB();
b.dispA();
ClassC c = new ClassC();
c.dispC();
c.dispA();
ClassD d = new ClassD();
d.dispD();
d.dispA();
}
}Unit-2 Object and Classes

Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA

4. Multiple Inheritance:
Multiple inheritance is a feature of oops concept, where a class can inherit
properties of more than one parent class.
It can be implemented by using Interface.
Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted
complexity when further extending the class.
Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
5. Hybrid Inheritance:
In simple term we can say that Hybrid Inheritance is a combination of Single and
Multiple inheritance.
It can be implemented by using Interface.
Flow diagram of the Hybrid inheritance will look like below. As you
can ClassA will be acting as the Parent class for ClassB & ClassC and ClassB &
ClassC will be acting as Parent for ClassD.

Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation, the variables
of a class will be hidden from other classes, and can be accessed only through the
methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.

Provide public setter and getter methods to modify and view the variables values.

/* File name : EncapTest.java */publicclassEncapTest{


privateString name;
privateString idNum;
privateint age;

publicint getAge(){
return age;
}

publicString getName(){
return name;
}

publicString getIdNum(){
return idNum;
}

publicvoid setAge(int newAge){


age = newAge;
}

publicvoid setName(String newName){


name = newName;
}

publicvoid setIdNum(String newId){


idNum = newId;
}}
/* File name : RunEncap.java */publicclassRunEncap{

publicstaticvoid main(String args[]){


EncapTest encap =newEncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : "+ encap.getName()+" Age : "+ encap.getAge());


}}
This will produce the following result −
Output
Name : James Age : 20

The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters and
setters. Therefore, any class that wants to access the variables should access them
through these getters and setters.

Java - Polymorphism
Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism allows us to perform a single action in different
ways. In other words, polymorphism allows you to define one interface and have
multiple implementations. The word “poly” means many and “morphs” means
forms, So it means many forms.
Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to refer to a
child class object.
Types of Java polymorphism
In Java polymorphism is mainly divided into two types:
 Compile-time Polymorphism
 Runtime Polymorphism
Compile-Time Polymorphism
It is also known as static polymorphism. This type of polymorphism is achieved by
function overloading or operator overloading.

Method Overloading

When there are multiple functions with the same name but different parameters then
these functions are said to be overloaded. Functions can be overloaded by changes
in the number of arguments or/and a change in the type of arguments.
// Java Program for Method overloading
// By using Different Types of Arguments

// Class 1
// Helper class
class Helper {
// Method with 2 integer parameters
static int Multiply(int a, int b)
{

// Returns product of integer numbers


return a * b;
}

// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{

// Returns product of double numbers


return a * b;
}
}

// Class 2
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Calling method by passing


// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}

Operator Overloading
It is a feature in C++ where the operators such as +, -, *, etc. can be given additional
meanings when applied to user-defined data types.
It is also known as Dynamic Method Dispatch. It is a process in which a function
call to the overridden method is resolved at Runtime. This type of polymorphism is
achieved by Method Overriding. Method overriding, on the other hand, occurs when
a derived class has a definition for one of the member functions of the base class.
That base function is said to be overridden.
// Java Program for Method Overriding

// Class 1
// Helper class
class Parent {

// Method of parent class


void Print()
{

// Print statement
System.out.println("parent class");
}
}

// Class 2
// Helper class
class subclass1 extends Parent {

// Method
void Print() { System.out.println("subclass1"); }
}

// Class 3
// Helper class
class subclass2 extends Parent {

// Method
void Print()
{

// Print statement
System.out.println("subclass2");
}
}

// Class 4
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of class 1


Parent a;

// Now we will be calling print methods


// inside main() method

a = new subclass1();
a.Print();

a = new subclass2();
a.Print();
}
}
Polymorphism in Java is a concept that allows objects of different classes to be
treated as objects of a common class. It enables objects to behave differently based
on their specific class type.

Advantages of Polymorphism in Java

1. Increases code reusability by allowing objects of different classes to be treated


as objects of a common class.
2. Improves readability and maintainability of code by reducing the amount of
code that needs to be written and maintained.
3. Supports dynamic binding, enabling the correct method to be called at runtime,
based on the actual class of the object.
4. Enables objects to be treated as a single type, making it easier to write generic
code that can handle objects of different types.

Disadvantages of Polymorphism in Java

1. Can make it more difficult to understand the behavior of an object, especially if


the code is complex.
2. This may lead to performance issues, as polymorphic behavior may require
additional computations at runtime.
3.
Interface
An interface is a reference type in Java. It is similar to class. It is a collection of
abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.
Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default
methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes
and behaviors of an object. And an interface contains behaviors that a class
implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
An interface is similar to a class in the following ways −

An interface can contain any number of methods.


An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in
a directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in
an interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.

Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface −
Example
Following is an example of an interface −
/* File name : NameOfInterface.java */import java.lang.*;// Any number of import
statements
publicinterfaceNameOfInterface{
// Any number of final, static fields
// Any number of abstract method declarations\}
Interfaces have the following properties −
An interface is implicitly abstract. You do not need to use
the abstract keyword while declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword
is not needed.
Methods in an interface are implicitly public.

Example
/* File name : Animal.java */interfaceAnimal{
publicvoid eat();
publicvoid travel();}
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform
all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the
declaration.
Example
/* File name : MammalInt.java */publicclassMammalIntimplementsAnimal{

publicvoid eat(){
System.out.println("Mammal eats");
}

publicvoid travel(){
System.out.println("Mammal travels");
}

publicint noOfLegs(){
return0;
}

publicstaticvoid main(String args[]){


MammalInt m =newMammalInt();
m.eat();
m.travel();
}}
This will produce the following result −
Output
Mammal eats
Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed
Checked exceptions should not be declared on implementation methods other
than the ones declared by the interface method or subclasses of those declared
by the interface method.

The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.

An implementation class itself can be abstract and if so, interface methods need not be
implemented.

When implementation interfaces, there are several rules −


 A class can implement more than one interface at a time.

 A class can extend only one class, but implement many interfaces.

 An interface can extend another interface, in a similar way as a class can extend
another class.

Extending Interfaces
An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
Example
// Filename: Sports.javapublic
interfaceSports{
publicvoid setHomeTeam(String name);
publicvoid setVisitingTeam(String name);}
// Filename: Football.javapublic
interfaceFootballextendsSports{
publicvoid homeTeamScored(int points);
publicvoid visitingTeamScored(int points);
publicvoid endOfQuarter(int quarter);}
// Filename: Hockey.javapublic
interfaceHockeyextendsSports{
publicvoid homeGoalScored();
publicvoid visitingGoalScored();
publicvoid endOfPeriod(int period);
publicvoid overtimePeriod(int ot);}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class
that implements Hockey needs to implement all six methods. Similarly, a class that
implements Football needs to define the three methods from Football and the two
methods from Sports.
Extending Multiple Interfaces
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent
interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-
separated list.
For example, if the Hockey interface extended both Sports and Event, it would be
declared as −
Example
publicinterfaceHockeyextendsSports,Event
Tagging Interfaces
The most common use of extending interfaces occurs when the parent interface does
not contain any methods. For example, the MouseListener interface in the
java.awt.event package extended java.util.EventListener, which is defined as −
Example
package java.util;publicinterfaceEventListener{}
An interface with no methods in it is referred to as a tagging interface. There are two
basic design purposes of tagging interfaces −
Creates a common parent − As with the EventListener interface, which is extended
by dozens of other interfaces in the Java API, you can use a tagging interface to create
a common parent among a group of interfaces. For example, when an interface
extends EventListener, the JVM knows that this particular interface is going to be
used in an event delegation scenario.
Adds a data type to a class − This situation is where the term, tagging comes from.
A class that implements a tagging interface does not need to define any methods
(since the interface does not have any), but the class becomes an interface type
through polymorphism.

What is marker interface?


An interface that does not contain methods, fields, and constants is
known as marker interface. In other words, an empty interface is
known as marker interface or tag interface. It delivers the run-
time type information about an object. It is the reason that
the JVM and compiler have additional information about an object.
The Serializable and Cloneable interfaces are the example of
marker interface. In short, it indicates a signal or command to the
JVM.
The declaration of marker interface is the same as interface in Java
but the interface must be empty. For example:

1. public interface Serializable


2. {
3.
4. }
There are the two alternatives of marker interface that produces the
same result as the marker interface

o Internal Flags: It can be used in place of marker interface to


indicate any specific operation.
o Annotations: Since Java 5, marker interfaces are
omitted. Instead of marker interface, Java 5 provides
the annotations to achieve the same results. It allows
flexible metadata capability. Therefore, by applying
annotations to any class, we can perform specific action.

Uses of Marker Interface


Marker interface is used as a tag that inform the Java compiler by a message so that it
can add some special behavior to the class implementing it. Java marker interface are
useful if we have information about the class and that information never changes, in
such cases, we use marker interface represent to represent the same. Implementing an
empty interface tells the compiler to do some operations.

It is used to logically divide the code and a good way to categorize code. It is more
useful for developing API and in frameworks like Spring.

Built-in Marker Interface


In Java, built-in marker interfaces are the interfaces that are already present in
the JDK and ready to use. There are many built-in marker interfaces some of them
are:

o Cloneable Interface
o Serializable Interface
o Remote Interface

Let's discuss one by one in detail.

Cloneable Interface
Cleanable interface in Java is also a marker interface that belong
to java.lang package. It generates replica (copy) of an object with different name.
We can implement the interface in the class of which class object to be cloned. It
indicates the clone() method of the Object class. If we do not implement the
Cloneable interface in the class and invokes the clone() method, it throws
the ClassNotSupportedException.

Note that a class that implements the Cloneable interface must override the clone()
method with a public method. Let's see an example.

Product.java

1. import java.util.Scanner;
2. public class Product implements Cloneable
3. {
4. int pid;
5. String pname;
6. double pcost;
7. //Product class constructor
8. public Product (int pid, String pname, double pcost)
9. {
10. this.pid = pid;
11. this.pname = pname;
12. this.pcost = pcost;
13. }
14. //method that prints the detail on the console
15. public void showDetail()
16. {
17. System.out.println("Product ID: "+pid);
18. System.out.println("Product Name: "+pname);
19. System.out.println("Product Cost: "+pcost);
20. }
21. public static void main (String args[]) throws CloneNotSupportedException
22. {
23. //reading values of the product from the user
24. Scanner sc = new Scanner(System.in);
25. System.out.print("Enter product ID: ");
26. int pid = sc.nextInt();
27. System.out.print("Enter product name: ");
28. String pname = sc.next();
29. System.out.print("Enter product Cost: ");
30. double pcost = sc.nextDouble();
31. System.out.println("-------Product Detail--------");
32. Product p1 = new Product(pid, pname, pcost);
33. //cloning the object of the Product class using the clone() method
34. Product p2 = (Product) p1.clone();
35. //invoking the method to print detail
36. p2.showDetail();
37. }
38. }

Output:

Enter product ID: 139872


Enter product name: Printer
Enter product Cost: 3459.67
-------Product Detail--------
Product ID: 139872
Product Name: Printer
Product Cost: 3459.67

Serializable Interface
It is a marker interface in Java that is defined in the java.io package. If we want to
make the class serializable, we must implement the Serializable interface. If a
class implements the Serializable interface, we can serialize or deserialize the state of
an object of that class.

Serialization (converting an object into byte stream) is a mechanism in


which object state is read from the memory and written into a
file or database. Deserialization (converting byte stream into an object) is the
opposite of serialization means that object state reading from a file or
database and written back into memory is called deserialization of
object.

Serialization (writing) can be achieved with the ObjectOutputStream class


and deserialization (reading) can be achieved with
the ObjectInputStream class.

Let's see example of serialization and deserialization.

Example of Serialization

1. import java.io.Serializable;
2. public class Employee implements Serializable
3. {
4. int empid;
5. String empname;
6. public Employee(int empid, String empname)
7. {
8. this.empid = empid;
9. this.empname = empname;
10. }
11. }

SerializationExample.java
1. import java.io.*;
2. class SerializationExample
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. //Creating the object
9. Employee emp =new Employee(1187345,"Andrew");
10. //Creating stream and writing the object
11. FileOutputStream fout=new FileOutputStream("employee data.txt")
;
12. ObjectOutputStream out=new ObjectOutputStream(fout);
13. out.writeObject(emp);
14. out.flush();
15. //closing the stream
16. out.close();
17. System.out.println("Data has been read from the file.");
18. }
19. catch(Exception e)
20. {
21. e.printStackTrace();
22. }
23. }
24. }

Output:

Data has been read from the file.

Example of Deserialization

Let's deserialize the object state.


DeserializationExample.java

1. import java.io.*;
2. class DeserializationExample
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. //Creating stream to read the object
9. ObjectInputStream in=new ObjectInputStream(new FileInputStrea
m("employee data.txt"));
10. Employee emp=(Employee)in.readObject();
11. //printing the data of the serialized object
12. System.out.println(emp.empid+" "+emp.empname);
13. //closing the stream
14. in.close();
15. }
16. catch(Exception e)
17. {
18. e.printStackTrace();
19. }
20. }
21. }

Output:

1187345 Andrew

Remote Interface

Employee.java
. Remote interface is a marker interface that belong
to java.rmi package. It marks an object as remote that can be
accessed from another machine (host). We must implement the
Remote interface if we want to make an object as remote. It
identifies the interfaces whose methods can be invoked from a non-
local JVM. Any remote object must implement the interface directly
or indirectly.

Let's define a Remote interface and implement it in a Java program.

Defining Remote interface

1. import java.rmi.*;
2. public interface AddAll extends Remote
3. {
4. public int add(int r, int s)throws RemoteException;
5. }

Implement the Remote Interface

There are following two ways to implement the Remote interface:

o By extending the UnicastRemoteObject class


o By using the exportObject() method of the
UnicastRemoteObject class

AddAllRemote.java

1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AddAllRemote extends UnicastRemoteObject implem
ents Adder
4. {
5. AddAllRemote()throws RemoteException
6. {
7. super();
8. }
9. public int add(int r, int s)
10. {
11. return r+s;
12. }

Create and Start the Remote Application

Server.java

1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class Server
4. {
5. public static void main(String args[])
6. {
7. try
8. {
9. AddAll stub=new AddAllRemote();
10. Naming.rebind("rmi://localhost:5000/sak",stub);
11. }
12. catch(Exception e)
13. {
14. System.out.println(e);
15. }
16. }
17. }

Create and Start the Client Application

Client.java

1. import java.rmi.*;
2. public class Client
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. AddAll stub=(AddAll)Naming.lookup("rmi://localhost:5000/sak");
9. System.out.println(stub.add(29,18));
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. }

Custom Marker Interface


Apart from built-in marker interface, Java also allows us to create
own marker interface. Let's see an example.

CustomMarkerInterfaceExample.java

1. //custom marker interface


2. interface Car
3. {
4.
5. }
6. //custom marker interface
7. interface Engine
8. {
9.
10. }
11. //class that implements the Car marker interface
12. class Vehicle implements Car
13. {
14. static void isVehicle()
15. {
16. System.out.println("Car is a vehicle.");
17. }
18. }
19. //class that implements the Engine marker interface
20. class Status implements Engine
21. {
22. static void isWorking()
23. {
24. System.out.println("Yes, engine is working.");
25. }
26. }
27. //main class
28. public class CustomMarkerInterfaceExample
29. {
30. public static void main(String args[])
31. {
32. //invoking the methods of the class
33. Vehicle.isVehicle();
34. Status.isWorking();
35. }
36. }

Output:

Car is a vehicle.
Yes, engine is working.
A functional interface is an interface that contains only one abstract method. They
can have only one functionality to exhibit. From Java 8 onwards, lambda
expressions can be used to represent the instance of a functional interface. A
functional interface can have any number of default
methods. Runnable, ActionListener, and Comparable are some of the examples of
functional interfaces.
Functional Interface is additionally recognized as Single Abstract Method
Interfaces. In short, they are also known as SAM interfaces. Functional interfaces
in Java are the new feature that provides users with the approach of fundamental
programming.
Functional interfaces are included in Java SE 8 with Lambda expressions and
Method references in order to make code more readable, clean, and straightforward.
Functional interfaces are interfaces that ensure that they include precisely only one
abstract method. Functional interfaces are used and executed by representing the
interface with an annotation called @FunctionalInterface. As described earlier,
functional interfaces can contain only one abstract method. However, they can
include any quantity of default and static methods.

// Java program to demonstrate functional interface

class Test {
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable() {
@Override public void run()
{
System.out.println("New thread created");
}
}).start();
}
}

// Java program to demonstrate Implementation of


// functional interface using lambda expressions

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

// lambda expression to create the object


new Thread(() -> {
System.out.println("New thread created");
}).start();
}
}

You might also like