0% found this document useful (0 votes)
25 views

Java unit-3

Uploaded by

Bhuvaneshwari M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Java unit-3

Uploaded by

Bhuvaneshwari M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Class Notes

INTERNET PROGRAMMING
UNIT-3
SYLLABUS:

Inheritance, Interfaces and Packages

Defining a subclass – Subclass constructor – Multilevel inheritance –


Hierarchical Inheritance – Defining Interfaces – Extending Interfaces –
Implementing Interfaces – Java APF Packages – creating a package –
Accessing and Using a package – Adding a class to a package – Hiding
Classes.

DEFINING A SUBCLASS :

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

also a base class or a parent class.

Syntax:

class Subclass-name extends Superclass-name


1. {
2

2. //methods and fields


3. }

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.

Example:

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

}
3

Output:

Programmer salary is:40000.0

Bonus of programmer is:10000

SUBCLASS CONSTRUCTOR:

A subclass inherits all the members (fields, methods, and nested classes) from
its superclass. Constructors are not members, so they are not inherited by subclasses,
but the constructor of the superclass can be invoked from the subclass.

● Constructors in Java are used to initialize the values of the attributes of the
object serving the goal to bring Java closer to the real world.

Example:

// Class 1

// Super class

class Base {

// Constructor of super class

Base()

// Print statement

System.out.println(

"Base Class Constructor Called ");

// Class 2
4

// Sub class

class Derived extends Base

// Constructor of subclass

Derived()

// Print statement

System.out.println(

"Derived Class Constructor Called ");

// Class 3

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating an object of sub class

// inside main() method

Derived d = new Derived();

// Note: Here first super class constructor will be

// called there after derived(sub class) constructor

// will be called

Output

Base Class Constructor Called


5

Derived Class Constructor Called.

MULTILEVEL INHERITANCE:

In MultiLevel Inheritance in Java, a class extends to another class that is


already extended from another class.

For example;

if there is a class A that extends class B and class B extends from another class C, then
this scenario is known to follow Multi-level Inheritance.

Example:

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();


6

d.weep();

d.bark();

d.eat();

}}

Output:

weeping...

barking...

eating…

HIERARCHICAL INHERITANCE:

Hierarchical inheritance in Java is a type of inheritance in which the same class


is inherited by more than one class. In other words, when several classes inherit their
features from the same class, the type of inheritance is said to be hierarchical.

Example:
7

// Java program to illustrate the

// concept of Hierarchical inheritance

class A {

public void print_A() { System.out.println("Class A"); }

class B extends A {

public void print_B() { System.out.println("Class B"); }

class C extends A {

public void print_C() { System.out.println("Class C"); }

class D extends A {

public void print_D() { System.out.println("Class D"); }

// Driver Class

public class Test {

public static void main(String[] args)

B obj_B = new B();

obj_B.print_A();

obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();


8

obj_D.print_A();

obj_D.print_D();

Output:

Class A

Class B

Class A

Class C

Class A

Class D

DEFINING INTERFACE:
● An Interface in Java programming language is defined as an abstract type used to
specify the behavior of a class.
● An interface in Java is a blueprint of a behavior.
● A Java interface contains static constants and abstract methods.

Syntax for Java Interfaces:

interface {

// declare constant fields

// declare methods that abstract

// by default.

Relationship Between Class and Interface:

A class can extend another class similar to an interface can extend another interface. But only
a class can extend to another interface, and vice-versa is not allowed.
9

Example:

interface Polygon {

void getArea(int length, int breadth);

// implement the Polygon interface

class Rectangle implements Polygon {

// implementation of abstract method

public void getArea(int length, int breadth) {

System.out.println("The area of the rectangle is " + (length * breadth));

class Main {

public static void main(String[] args) {

Rectangle r1 = new Rectangle();

r1.getArea(5, 6);

}
10

Output:

The area of the rectangle is 30

EXTENDING INTERFACE:
● 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.

Example:

interface A {

void funcA();

interface B extends A {

void funcB();
11

class C implements B {

public void funcA() {

System.out.println("This is funcA");

public void funcB() {

System.out.println("This is funcB");

public class Demo {

public static void main(String args[]) {

C obj = new C();

obj.funcA();

obj.funcB();

Output:

This is funcA

This is funcB

IMPLEMENTING INTERFACE:
● In java, an interface is implemented by a class.
● The class that implements an interface must provide code for all the methods
defined in the interface, otherwise, it must be defined as an abstract class.
● Like abstract classes, we cannot create objects of interfaces.

● The class uses a keyword implements to implement an interface.


12

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.

Syntax :

class className implements InterfaceName{

...

boby-of-the-class

...

Example:

interface Human {

void learn(String str);

void work();

int duration = 10;

class Programmer implements Human{

public void learn(String str) {

System.out.println("Learn using " + str);

public void work() {

System.out.println("Develop applications");

}
13

public class HumanTest {

public static void main(String[] args) {

Programmer trainee = new Programmer();

trainee.learn("coding");

trainee.work();

JAVA APF PACKAGE:


A Java package is a set of related classes, interfaces, and sub-packages with common
characteristics, such as the same data types or performing similar operations on the
data.

● Java packages are essential in managing the complexity of large-scale Java


applications.

Types of packages in Java:


14

Built-in Packages:

These packages consist of a large number of classes which are a part of Java
API.Some of the commonly used built-in packages are:

1) java.lang:

Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.

2) java.io:

Contains classed for supporting input / output operations.

3) java.util:

Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.

4) java.applet:

Contains classes for creating Applets.

5) java.awt:

Contain classes for implementing the components for graphical user interfaces (like
button , menus etc).

6) java.net:

Contain classes for supporting networking operations.


15

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

package myPackage;

public class MyClass

public void getNames(String s){

System.out.println(s);

Important points:

● Every class is part of some package.


● If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
● All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
● If package name is specified, the file must be in a subdirectory called name (i.e.,
the directory name must match the package name).
● We can access public classes in another (named) package using:
package-name.class-name.

CREATING A PACKAGE:
In Java, a package is a group of classes, interfaces, enumeration, and annotations.
Java contains many predefined packages such as java.lang, java.io, java.net, etc.

We use package for the following reasons:

1. The package makes the search easier for the classes and interfaces.
2. It provides a fully qualified name that avoids naming conflicts.
3. It also controls access.
4. It organizes classes in a folder structure.
5. It improves code reusability.
17

6. Programmer can group classes and interfaces into a related package.

To create a package, follow the steps given below:

1. Choose a package name according to the naming convention.


2. Write the package name at the top of every source file (classes, interface,
enumeration, and annotations).
3. Remember that there must be only one package statement in each source file..

**Creating a package is a simple task as follows**

1. Choose the name of the package


2. Include the package command as the first line of code in your Java Source File.
3. The Source file contains the classes, interfaces, etc you want to include in the
package
4. Compile to create the Java package.:

To create a user defined package the following steps should be involved :-

1: Declare the package at the beginning of a file using

the syntax :-

"package packageName;"
18

2: Define the class that is to be put in the package &

declare it public.

3: Create a subdirectory under the directory where the

main source files are stored.

4: Store the listing as the classname.java file in the

subdirectory created.

5: Compile the file. This create .class file in the subdirectory.

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

ACCESSING AND USING PACKAGES:

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.
19

1) Using packagename.*

● If you use a package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
● The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of packages that import the packagename.*

1. //save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

● //save by B.java

package mypack;
20

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

Output:Hello

2) Using packagename.classname:

If you import package.classname then only the declared class of this package will be
accessible.

Example of package by import package.classname:

● //save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

● //save by B.java

package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();
21

Output:Hello

3) Using fully qualified name:

If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

● It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Example of package by import fully qualified name:

● //save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

● //save by B.java

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

obj.msg();

}
Output:Hello
22

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.
● It is simple to add a class to an existing package. Consider the following
package :

package p1

public Class A

// body of A

The package p1 contains one public class by name A. Suppose we want to add another
class B to this package. This can be done as follows :

1. Define the class and make it public.

2. Place the package statement

Package p1 ;

Before the class definition as follows :

Package p1

Public Class B

// body of B

3. Store this as B.java file under the directory p1.


23

4. Compile B.java file. This will create a B.class file and place it in the directory
p1.

Now , the package p1 will contain both the classes A and B . The statement like

import p1. * ;

will import both of them.

● Syntax:

import packageName.ClassName;

Example:

package myPackage;

import java.util.Scanner;

public class ImportingExample

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);

HIDING CLASSES :
● When we want to import a package using

import packagename.*;

then all public classes are imported.

● If we want to hide classes from accessing from outside of the package ,then
such classes should be declared “not public”.

e.g. : package p1;


24

public class X

{ //body of class }

class Y { //body of class }

import p1.*;

X objx; // ok ,class X is available here

Y objy; // Not Ok,class y is not available here.

CLASS PATH:

● The compiler and the interpreter searches for the classes

in the current directory and the directory ,which consists

JDK class files.

● All JDK class files and the current directory are

automatically set in your class path.

● But when we want save our class file any other directory

in place of JDK ‘s bin folder, then we have to set

classpath to run that class file.

● A classpath is a list of directories ,which compiler and

interpreter use to search for the respective class file.

CLASS PATH:

We can set path as following:

1.javac –d classpath filename

2.set path=“c:\program files\java\jdk1.2\bin”;

3.Globally path set:

follow steps given below:


25

You might also like