0% found this document useful (0 votes)
2 views43 pages

Unit-2(OOPS With Java)

The document provides an overview of key concepts in Java, including inheritance, interfaces, packages, abstract classes, and object cloning. It explains various types of inheritance (single, multilevel, hierarchical, and multiple through interfaces), the role of the Object class, and the use of abstract classes and interfaces. Additionally, it covers the organization of classes into packages, the advantages and disadvantages of object cloning, and the setup of the CLASSPATH environment variable for Java applications.

Uploaded by

gowolo4077
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)
2 views43 pages

Unit-2(OOPS With Java)

The document provides an overview of key concepts in Java, including inheritance, interfaces, packages, abstract classes, and object cloning. It explains various types of inheritance (single, multilevel, hierarchical, and multiple through interfaces), the role of the Object class, and the use of abstract classes and interfaces. Additionally, it covers the organization of classes into packages, the advantages and disadvantages of object cloning, and the setup of the CLASSPATH environment variable for Java applications.

Uploaded by

gowolo4077
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

Inheritance, Interfaces,

and Packages (Unit-2)

Vaibhav Vats
Inheritance
• It is the mechanism in java by which one class is allowed to inherit the
features(fields and methods) of another class.
• Super Class: The class whose features are inherited is known as superclass(or a
base class or a parent class).
• Sub Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
• The keyword used for inheritance is extends.
class derived-class extends base-class
{ //methods and fields }
1. Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass. In the image below, class A serves as a base class for the derived
class B.
class one {
public void printTest() { [Link]("Geeks"); }
}
class two extends one {
public void printMore() { [Link]("for"); }
}
2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a
base class and as well as the derived class also act as the base class to other class. In the
below image, class A serves as a base class for the derived class B, which in turn serves as
a base class for the derived class C.
class one {
public void printTest() { [Link](“Test From One"); }
}
class two extends one {
public void printMore() { [Link](“Test from Two"); }
}
class three extends two {
public void printTest() {[Link](“Test From Three");}
}
3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass. In the below image, class A serves as a base class for the derived class B, C and D.
class A {
public void print_A() { [Link]("Class A"); }
}
class B extends A {
public void print_B() { [Link]("Class B"); }
}
class C extends A {
public void print_C() { [Link]("Class C"); }
}
class D extends A {
public void print_D() { [Link]("Class D"); }
}
4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces.
interface one {
public void printTest();
}
interface two extends one {
public void printData();
}
class child implements two {
@Override public void printTest()
{ [Link]("Test"); }

public void printData() { [Link]("Data"); }


}
• If your method overrides one of its superclass's methods, you can invoke the overridden method
through the use of the keyword super. You can also use super to refer to a hidden field. Consider this
class, Superclass:

public class Superclass {


public void printMethod() { [Link]("Printed in Superclass."); }
}

public class Subclass extends Superclass {


// overrides printMethod in Superclass
public void printMethod() {
[Link]();
[Link]("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
[Link](); }
}
constructors in sub classes
• If we want to call base class constructor in subclass then we have to use super().
class Base {
int x;
Base(int _x) { x = _x; }
}
class Derived extends Base {
int y;
Derived(int _x, int _y) { super(_x); y = _y; }
void Display() { [Link]("x = "+x+", y = "+y); }
}

public class Main {


public static void main(String[] args) {
Derived d = new Derived(10, 20);
[Link](); }
}
Object class
• Every class in Java is directly or indirectly derived from the Object class. If a Class
does not extend any other class then it is direct child class of Object and if
extends other class then it is an indirectly derived. Therefore the Object class
methods are available to all Java classes. Hence Object class acts as a root of
inheritance hierarchy in any Java Program.
• Class Object is the root of the class hierarchy. Every class has Object as a
superclass. All objects, including arrays, implement the methods of this class.
• Object class is present in [Link] package.
ABSTRACT CLASSES
• An abstract class is a class that is declared abstract—it may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be
subclassed.
• Or a class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods (method with the
body).
• Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
public abstract class GraphicObject {
// declare fields
int x, y;
...
// declare nonabstract methods
void moveTo(int newX, int newY) {
...
} Classes Rectangle, Line, Bezier, and Circle Inherit from GraphicObject

// declare abstract methods


abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
INTERFACE
• an interface is a reference type, similar to a class, that can
contain only constants, method signatures, default methods, static methods, and
nested types. Method bodies exist only for default methods and static methods.
Interfaces cannot be instantiated—they can only be implemented by classes
or extended by other interfaces.

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
interface Bicycle {

// wheel revolutions per minute


void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);


}
class ACMEBicycle implements Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

// The compiler will now require that methods


// changeCadence, changeGear, speedUp, and applyBrakes
// all be implemented. Compilation will fail if those methods are missing from this class.

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
[Link]("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
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.

// Filename: [Link]
public interface Sports {
void setHomeTeam(String name);
void setVisitingTeam(String name);
}
// Filename: [Link]
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: [Link]
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
Object Cloning
• Object cloning refers to the creation of an exact copy of an object. It creates a new
instance of the class of the current object and initializes all its fields with exactly the
contents of the corresponding fields of this object.
• The clone() method of Object class is used to clone an object.
• The [Link] interface must be implemented by the class whose object clone
we want to create. If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
• The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:
• protected Object clone() throws CloneNotSupportedException
• The clone() method saves the extra processing task for creating the exact copy of an object. If
we perform it by using the new keyword, it will take a lot of processing time to be performed
that is why we use object cloning.
Advantage of Object cloning
• Although [Link]() has some design issues but it is still a popular and easy way of copying
objects. Following is a list of advantages of using clone() method:
• You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-
line long clone() method.
• It is the easiest and most efficient way for copying objects, especially if we are applying it to an
already developed or an old project. Just define a parent class, implement Cloneable in it,
provide the definition of the clone() method and the task will be done.
• Clone() is the fastest way to copy array.
Disadvantage of Object cloning

• To use the [Link]() method, we have to change a lot of syntaxes to our code, like implementing a
Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and
finally, calling [Link]() etc.

• We have to implement cloneable interface while it doesn't have any methods in it. We just have to use
it to tell the JVM that we can perform clone() on our object.

• [Link]() is protected, so we have to provide our own clone() and indirectly call [Link]()
from it.

• [Link]() doesn't invoke any constructor so we don't have any control over object construction.

• If you want to write a clone method in a child class then all of its superclasses should define the clone()
method in them or inherit it from another parent class. Otherwise, the [Link]() chain will fail.

• [Link]() supports only shallow copying but we will need to override it if we need deep cloning.
class Student18 implements Cloneable{
int rollno;
String name;

Student18(int rollno,String name){


[Link]=rollno;
[Link]=name;
}

public Object clone()throws CloneNotSupportedException{


return [Link]();
}
public static void main(String args[]){
try{
Student18 s1=new Student18(101,"amit");

Student18 s2=(Student18)[Link]();

[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);

}catch(CloneNotSupportedException c){}

}
}
Package
• A package is a namespace that organizes a set of related classes and
interfaces. To keep things organized by placing related classes and interfaces
into packages. or
• Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces.
• All we need to do is put related classes into packages. After that, we can simply write an
import class from existing packages and use it in our program. A package is a container
of a group of related classes where some of the classes are accessible are exposed and
others are kept for internal purpose. We can reuse existing classes from the packages as
many time as we need it in our program.
• Adding a class to a Package : We can add more classes to a created package by using
package name at the top of the program and saving it in the package directory. We
need a new java file to define a public class, otherwise we can add the new class to an
existing .java file and recompile it.
• Subpackages: Packages that are inside another package are the subpackages. These are
not imported by default, they have to imported explicitly. Also, members of a
subpackage have no access privileges, i.e., they are considered as different package for
protected and default access specifiers.

import [Link].*;

• util is a subpackage created inside java package.


• Accessing classes inside a package
// import the Vector class from util package.
import [Link];

// import all the classes from util package


import [Link].*;

• First Statement is used to import Vector class from util package which is contained inside java.
• Second statement imports all the classes from util package.

// All the classes and interfaces of this package


// will be accessible but not subpackages.
import package.*;

// Only mentioned class of this package will be accessible.


import [Link];
• Types of packages:
1. Built-in Packages
2. User-defined packages

• 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.
• User-defined packages
These are the packages that are defined by the user. First we create a directory myPackage (name should
be same as the name of the package). Then create the MyClass inside the directory with the first
statement being the package names.

// Name of the package must be same as the directory


// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
[Link](s);
}
}
• Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */


import [Link];

public class PrintName


{
public static void main(String args[])
{
// Initializing the String variable with a value
String name = "PackageTest";

// Creating an instance of class MyClass in the package.


MyClass obj = new MyClass();

[Link](name);
}
}
• The package name is closely associated with the directory structure used to store
the classes.

• The classes (and other entities) belonging to a specific package are stored
together in the same directory.

• Furthermore, they are stored in a sub-directory structure specified by its package


name. For example, the class Circle of package [Link].project1.

• subproject2 is stored as “$BASE_DIR\com\zzz\project1\subproject2\[Link]”,


where $BASE_DIR denotes the base directory of the package. Clearly, the “dot” in
the package name corresponds to a sub-directory of the file system.
• The base directory ($BASE_DIR) could be located anywhere in the file system.
Hence, the Java compiler and runtime must be informed about the location of
the $BASE_DIR so as to locate the classes.

• This is accomplished by an environment variable called CLASSPATH.

• CLASSPATH is similar to another environment variable PATH, which is used by the


command shell to search for the executable programs.
• 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.

• To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH


• Step 1: Click on the Windows button and choose Control Panel. Select System.

• Step 2: Click on Advanced System Settings.


• Step 3: A dialog box will open. Click on Environment Variables.
• Step 4: If the CLASSPATH already exists in System Variables, click on the Edit
button then put a semicolon (;) at the end. Paste the Path of MySQL-Connector
[Link] file.
• If the CLASSPATH doesn't exist in System Variables, then click on the New button
and type Variable name as CLASSPATH and Variable value as C:\Program
Files\Java\jre1.8\MySQL-Connector [Link];.;
What is JAR?
• JAR stands for Java Archive. It's a file format based on the popular ZIP file format and is
used for aggregating many files into one.
• Although JAR can be used as a general archiving tool, the primary motivation for its
development was so that Java applets and their requisite components (.class files,
images and sounds) can be downloaded to a browser in a single HTTP transaction,
rather than opening a new connection for each piece.
• This greatly improves the speed with which an applet can be loaded onto a web page
and begin functioning. The JAR format also supports compression, which reduces the
size of the file and improves download time still further. Additionally, individual entries
in a JAR file may be digitally signed by the applet author to authenticate their origin.
• JAR is:
• the only archive format that is cross-platform
• the only format that handles audio and image files as well as class files
• backward-compatible with existing applet code
• an open standard, fully extendable, and written in java
• the preferred way to bundle the pieces of a java applet

• A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and
associated metadata and resources (text, images, etc.) into one file to distribute application software or
libraries on the Java platform.
• In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image
files, or directories. We can imagine a .jar file as a zipped file(.zip) that is created by using WinZip
software. Even, WinZip software can be used to extract the contents of a .jar . So you can use them for
tasks such as lossless data compression, archiving, decompression, and archive unpacking.
Create a JAR file
• In order to create a .jar file, we can use jar cf command in the following ways as
discussed below:
jar cf jarfilename inputfiles
• The options and arguments used in this command are:
• The c option indicates that you want to create a JAR file.
• The f option indicates that you want the output to go to a file rather than to stdout.
• jar-file is the name that you want the resulting JAR file to have. You can use any
filename for a JAR file. By convention, JAR filenames are given a .jar extension, though
this is not required.
• The input-file(s) argument is a space-separated list of one or more files that you
want to include in your JAR file. The input-file(s) argument can contain the
wildcard * symbol. If any of the "input-files" are directories, the contents of those
directories are added to the JAR archive recursively.
• Here, cf represents to create the file. For example , assuming our package pack is
available in C:\directory , to convert it into a jar file into the [Link] , we can give
the command as:

C:\> jar cf [Link] pack


Import and Static Import Naming Convention For Packages
• Import is a keyword in java and which is to indicate to include the package for a class or
interface, enum.
import [Link].*;
• The static import feature of Java 5 facilitate the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.
import static [Link].*;
• The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a
class without the class qualification. The import provides accessibility to classes and
interface whereas static import provides accessibility to static members of the class.
Networking [Link] package
• Java Networking is a concept of connecting two or more computing devices together so
that we can share resources.
• Java socket programming provides facility to share data between different computing
devices.
• Provides the classes for implementing networking [Link] [Link] package can
be roughly divided in two sections:
• A Low Level API, which deals with the following abstractions:
• Addresses, which are networking identifiers, like IP addresses.
• Sockets, which are basic bidirectional data communication mechanisms.
• Interfaces, which describe network interfaces.
• A High Level API, which deals with the following abstractions:
• URIs, which represent Universal Resource Identifiers.

• URLs, which represent Universal Resource Locators.

• Connections, which represents connections to the resource pointed to by URLs.

• The [Link] package supports two protocols,


1. TCP: Transmission Control Protocol provides reliable communication between
the sender and receiver. TCP is used along with the Internet Protocol referred as
TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by
allowing packet of data to be transferred along two or more nodes.

You might also like