Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Subject Name: Programming in Java


Subject Code: U19CST42

Prepared by:
Ms.V.SWATHILAKSHMI / AP /CSE
Mr.N.BALAJI / AP /CSE

Verified by: Approved by:

UNIT – II

Inheritance: Basic concepts - forms of inheritance - super key word – method overriding, abstract classes,
dynamic method dispatch - the Object class. Packages: Defining, Creating and Accessing, importing
packages. Interfaces: Defining, implementing, applying, variables and extending interfaces.

2MARKS
1. What is method overriding?
 If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java
 This is possible by defining a method in the subclass that has the same name , same arguments
and same returntype as a method in the superclass
 When the method is called, the method defined in the subclass is invoked and executed
instead of the one in the superclass.

2. What is the use of method overriding?


 to provide specific implementation of a method that is already provided by its super class
 runtime polymorphism

3. Write down the rules of method overriding?


 method must have same name as in the parent class
 Method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance)

4. What is method overloading and method overriding?


1. When a method in a class having the same method name with different arguments is said to be
method overloading.
2. Method overriding: When a method in a class having the same method name with same
arguments is said to be method overriding

5. Define final modifier?


 All methods and variables can be overriden by default in subclasses.
 To prevent the subclasses from overriding the members of the superclass, we can declare
them as final by using the keyword final as a modifier.
Example:
finalint SIZE = 100; final
void showstatus ()
{
……..

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

}
The functionality defined in this method will never be altered in any way

6. Define inheritance
 The mechanism of deriving a new from a from an old one is called inheritance The
old class is known as the base class or super class or parent class
 The new class is called the subclass or derived class or child class
 The inheritance allows subclasses to inherit all the variables and methods of their parent
classes

7. State the uses of inheritance


 Code Reusability
 Method Overriding (so runtime polymorphism can be achieved).

8. State the types of inheritance


 Single inheritance [only one super class]
 Hierarchical inheritance [ one super classes, many subclasses]
 Multilevel inheritance [derived from a derived class].

9. Why multiple inheritance is not supported in java


To reduce the complexity and simplify the language To
remove ambiguity

10. Syntax to extend a class


class subclassname extends superclassname
{
Variable declaration; Methods
declaration;
}
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname

11. Define super keyword


 The super keyword in java is a reference variable that is used to refer immediate parent class
object.
 Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable

12. What’s the difference between an interface and an abstract class?


Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods. Since Java 8,
non-abstract methods. it can have default and static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of abstract
implementation of interface. class.

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

5) The abstract keyword is used to The interface keyword is used to declare interface.
declare abstract class.

13. Define abstract class?


 Abstract classes are classes from which instances are usually not created. It is basically
used to contain common characteristics of its derived classes.
 Abstract classes are generally higher up the hierarchy and act as super classes. Methods
can also be declared as abstract. This implies that non-abstract classes must implement
these methods

14. Define abstract class?


1. Abstract classes are classes from which instances are usually not created. It is basically
used to contain common characteristics of its derived classes.
2. Abstract classes are generally higher up the hierarchy and act as super classes. Methods
can also be declared as abstract. This implies that non-abstract classes must implement
these methods

15. Define interface


An interface in java is a blueprint of a class. It has static constants and abstract methods only. It
is used to achieve fully abstraction and multiple inheritances in Java. It cannot be instantiated just
like abstract class

16. Syntax of defining interface


interface interfaceName
{
Variables declaration; Method
declaration;
}

17. Difference between class and interface


CLASS INTERFACE

The members of a class can be constant or The members of an interface are always declared
variables. as constant, i.e., their values are final.
The class definition can contain the code for each The methods in an interface are abstract in
of its methods. That is, the methods can be nature, i.e., there is no code associated with
abstract or non-abstract. them. It is later defined by the class that
implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public, It can only use the public access specifier.
private or protected.

18. What are the uses of interface?


 It is used to achieve fully abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

19. Explain the usage of java packages.


 This is a way to organize files when a project consists of multiple modules. It also helps
resolve naming conflicts when different packages have classes with the same names.
 Packages access level also allows you to protect data from being used by the non-
authorized classes.
20. Define packages in java?
 Packages provide a mechanism for grouping a variety of classes and / or interfaces
together.
 Grouping is based on functionality

Types of packages:
 Pre-defined packages or Java API packages
 User-defined packages

21. Define the syntax of defining package in java.
Syntax:
package [PackageName];
public class [ClassName]
{
//Body of the class
}
Example:
package firstPackage;
public class FirstClass
{
//Body of the class
}

22. Define access specifiers and its types in java?


Access specifiers specifies the type of access levels for the classes, variables, methods and
constructor

Types of access-specifiers:

 Default - Visible to the package, the default.


 Private - Visible to the class only.
 Public - Visible to the world.
 Protected -Visible to the package and all subclasses.

23. Explain the usage of java packages
 This is a way to organize files when a project consists of multiple modules. It also helps
resolve naming conflicts when different packages have classes with the same names.
 Packages access level also allows you to protect data from being used by the non-
authorized classes.

24. Can you call one constructor from another if a class has multiple
constructors
Yes. Use this() syntax

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

25. How can a subclass call a method or a constructor defined in a superclass?


Use the following syntax: super.myMethod(); To call a constructor of the super class, just write super();
in the first line of the subclass's constructor

26. What is a package?


To group set of classes into a single unit is known as packaging. Packages provide wide namespace ability.

27. What are the methods provided by the object class?


The Object class provides five methods that are critical when writing multithreaded Java programs:
∑ notify
∑ notifyAll
∑ wait (three versions)

28. What is the difference between superclass and subclass?


A super class is a class that is inherited whereas sub class is a class that does the inheriting.

29. Define superclass and subclass?


 Superclass is a class from which another class inherits.
 Subclass is a class that inherits from one or more classes

30. What is dynamic method dispatching in Java?


Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method
dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than
compile time.
 When an overridden method is called through a superclass reference, Java determines which version
(superclass/subclasses) of that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is made at run time.
 At run-time, it depends on 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
31. What is the Object class in Java?
 The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
 The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

5MARKS
1. Explain in detail about inheritance in java
 SYNOPSIS
 INTRODUCTION
 USE OF INHERITANCE
 FORMS OF INHERITANCE
 WHY NO MULTIPLE INHERITANCE
 SUPER KEYWORD
 EXAMPLE PROGRAMS

INTRODUCTION:
 The mechanism of deriving a new from a from an old one is called inheritance
 The old class is known as the base class or super class or parent class
 The new class is called the subclass or derived class or child class
 The inheritance allows subclasses to inherit all the variables and methods of their parent
classes

USE OF INHERITANCE:
 Code Reusability
 Method Overriding (so runtime polymorphism can be achieved).

FORMS OF INHERITANCE:
 Single inheritance [only one super class]
 Multiple inheritance [several super classes ]
 Hierarchical inheritance [ one super classes, many subclasses]
 Multilevel inheritance [derived from a derived class].
 Java does not directly implement multiple inheritances but by using the concept of
secondaryinheritance path in the form of interfaces.
The diagrammatical representation of the forms of inheritance is as follows:

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.

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

 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: As the name specifies, 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.

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);
}
}
OUTPUT:
Programmer salary is: 40000.0
Bonus of programmer is: 10000

TYPES OF INHERITANCE IN JAVA

SINGLE INHERITANCE

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

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.
EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

MULTILEVEL INHERITANCE
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.

EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

HIERARCHICAL INHERITANCE
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.

EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Hybrid Inheritance in Java


A hybrid inheritance is a combination of more than one types of inheritance. For example when class A
and B extends class C & another class D extends class A then this is a hybrid inheritance, because it is a
combination of single and hierarchical inheritance. Let me show you this diagrammatically:
C

|
---------------
↑ ↑
| |
A B

|
D

Example:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}
Output:
D

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.

USE OF SUPER:
 Super is used to refer immediate parent class instance variable
 super() is used to invoke immediate parent class constructor
 super is used to invoke immediate parent class method

2. Explain in detail about super keyword in java.


The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
 USE OF SUPER:
 Super is used to refer immediate parent class instance variable
 super() is used to invoke immediate parent class constructor
 super is used to invoke immediate parent class method
.
1) Super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.
EXAMPLE:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Dog d=new Dog();


d.printColor();
}}
Output:
black
white

2) Super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

Output:
eating...
barking...

3) Super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor.
EXAMPLE:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created

3. Explain in detail about method overriding in java.


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Use of Java Method Overriding
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method overriding.
EXAMPLE:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

class Vehicle{
void run(){
System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running

EXAMPLE OF METHOD OVERRIDING


In this example, we have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method are the same, and there
is IS-A relationship between the classes, so there is method overriding.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){
System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely
DIFFERENCE BETWEEN METHOD OVERLOADING AND METHOD OVERRIDING

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.

2) Method overloading is performed within Method overriding occurs in two classes that

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

class. have IS-A (inheritance) relationship.

3) In case of method overloading, parameter In case of method overriding, parameter must


must be different. be same.

4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

5) In java, method overloading can't be Return type must be same or covariant in


performed by changing return type of the method overridin
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

4. Explain in details about Dynamic Method Dispatch?


Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic
method dispatch is the mechanism by which a call to an overridden method is resolved at run time,
rather than compile time.
 When an overridden method is called through a superclass reference, Java determines which
version (superclass/subclasses) of that method is to be executed based upon the type of the
object being referred to at the time the call occurs. Thus, this determination is made at run
time.
 At run-time, it depends on 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 superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.

Advantages of dynamic method dispatch


1. It allows Java to support overriding of methods, which are important for run-time
polymorphism.
2. It allows a class to define methods that will be shared by all its derived classes, while also
allowing these sub-classes to define their specific implementation of a few or all of those
methods.
3. It allows subclasses to incorporate their own methods and define their implementation.

Example:
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Let us look at an example.


class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
This will produce the following result −
Output
Animals can move
Dogs can walk and run
5. Describe in details about packages?
INTRODUCTION:
 Packages provide a mechanism for grouping a variety of classes and / or interfaces together.
 Grouping is based on functionality Benefits of Packages:
 The classes contained in the packages of other programs can be reused.
In packages, classes can be unique compared with classes in other packages.
A package provides a way to hide classes.
Types of packages:
• Pre-defined packages or Java API packages
• User-defined packages
Java API packages:
A large number of classes grouped into different packages based on functionality.
Examples:
 java.lang
 java.util
 java.io
 java.awt
 .java.net
 java. applet etc.
Accessing Classes in a Package:
1. Fully Qualified class name: Example:java.awt.Color
2. import packagename.classname; Example: import java.awt.Color;
or
import packagename.*; Example: import java.awt.*;
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Import statement must appear at the top of the file, before any class declaration

Creating Your Own Package

1. Declare the package at the beginning of a file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory where the main
source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory

Syntax:
package [PackageName];
public class [ClassName]
{
//Body of the class
}

Example:
package firstPackage; public class FirstClass
{
//Body of the class
}

Example:
//Class in package package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
//Importing class from package import p1.*;
class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA(); obA.displayA();
}

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Creating Packages:
 Consider the following declaration: package firstPackage.secondPackage;
 This package is stored in subdirectory named firstPackage.secondPackage.
 A java package can contain more than one class definitions that can be declared as public.
 Only one of the classes may be declared public and that class name with .java extension is the
source file name.

Default Package:
• If a source file does not begin with the package statement, the classes contained in the source
file reside in the default package
• The java compiler automatically looks in the default package to find classes

Finding Packages:
1. By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
2. Specify a directory path using CLASSPATH environmental variable

CLASSPATH Environment Variable


• The compiler and runtime interpreter know how to find standard packages such as
java.lang and java.util
• The CLASSPATH environment variable is used to direct the compiler and interpreter to
where programmer defined imported packages can be found
• The CLASSPATH environment variable is an ordered list of directories and files
• To set the CLASSPATH variable we use the following command: set CLASSPATH=c:\
• Java compiler and interpreter searches the user defined packages from the above directory.
• To clear the previous setting we use: set CLASSPATH=

ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes, variables, methods and
constructor

Types of access-specifiers:

 Default - Visible to the package, the default.


 Private - Visible to the class only.
 Public - Visible to the world.
 Protected -Visible to the package and all subclasses.

Levels of Access Control:

public protected friendly (default) private

same class Yes Yes Yes Yes

Subclass in Yes Yes Yes No


the same
package

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Other class Yes Yes Yes No


in the
same package

Subclass in Yes Yes No No


other
packages

Non- subclass Yes No No No


in other
package

Example 1:
package my_package;
class A // package scope
{
// A’s public & private members
}
public class B // public scope
{
// B’s public and private members
}

Example 2:
package my_package;
class A
{
int get() { return data; } // package scope
public A(int d) { data=d;} // public scope
private int data; // private scope
}
class B
{
void f()
{
A a=new A(d);// OK A has package scope
int d=a.get(); // OK – get() has package scope
int d1=a.data;// Error! – data is private
}
}
6. Write short notes on interfaces.

INTERFACES
 An interface in java is a blueprint of a class. It has static constants and abstract methods only.
 The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body.
 It is used to achieve fully abstraction and multiple inheritances in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.

USE OF INTERFACE:

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

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

RELATIONSHIP BETWEEN CLASSES AND INTERFACES

As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface

CLASS INTERFACE
The members of a class can be constant or The members of an interface are always
varaibles. declared as constant, i.e., their values are final.

The class definition can contain the code for The methods in an interface are abstract
each of its methods. That is , the methods can be in nature, i.e., there is no code associated
abstract or non-abstract. with them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.

It can use various access specifiers like public, It can only use the public access specifier.
private or protected.

INTERFACE SYNTAX:
interface interfaceName
{
Variables declaration; Method declaration;
}
interface - keyword.
interfacename - any valid java variable.

SIMPLE EXAMPLE OF JAVA INTERFACE


In this example, Printable interface have only one method, its implementation is provided in the A
class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){ A6 obj = new A6();


Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

obj.print();
}
}

Output: Hello
MULTIPLE INHERITANCES IN JAVA BY INTERFACE
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){ A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:
Hello Welcome

7. DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

10MARKS

1. EXPLAIN IN DETAIL ABOUT INHERITANCE IN JAVA


 SYNOPSIS
 INTRODUCTION
 USE OF INHERITANCE
 FORMS OF INHERITANCE
 WHY NO MULTIPLE INHERITANCE
 SUPER KEYWORD
 EXAMPLE PROGRAMS

INTRODUCTION:
 The mechanism of deriving a new from a from an old one is called inheritance
 The old class is known as the base class or super class or parent class
 The new class is called the subclass or derived class or child class
 The inheritance allows subclasses to inherit all the variables and methods of their parent
classes

USE OF INHERITANCE:
 Code Reusability
 Method Overriding (so runtime polymorphism can be achieved).

FORMS OF INHERITANCE:
 Single inheritance [only one super class]
 Multiple inheritance [several super classes ]
 Hierarchical inheritance [ one super classes, many subclasses]
 Multilevel inheritance [derived from a derived class].
 Java does not directly implement multiple inheritances but by using the concept of
secondaryinheritance path in the form of interfaces.
The diagrammatical representation of the forms of inheritance is as follows:

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
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

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: As the name specifies, 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.

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);
}
}
OUTPUT:
Programmer salary is: 40000.0
Bonus of programmer is: 10000

TYPES OF INHERITANCE IN JAVA

SINGLE INHERITANCE

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

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.
EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

MULTILEVEL INHERITANCE
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.

EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

HIERARCHICAL INHERITANCE
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.

EXAMPLE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

Hybrid Inheritance in Java


A hybrid inheritance is a combination of more than one types of inheritance. For example when class A
and B extends class C & another class D extends class A then this is a hybrid inheritance, because it is a
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

combination of single and hierarchical inheritance. Let me show you this diagrammatically:
C

|
---------------
↑ ↑
| |
A B

|
D

Example:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}
Output:
D

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

WHY MULTIPLE INHERITANCES IS NOT SUPPORTED:


• To reduce the complexity and simplify the language
• To remove ambiguity

TYPES OF AMBUIGUITIES IN C++:


1) AMBUIGUITY IN MULTIPLE INHERITANCE:

2) AMBUIGUITY IN MULTI-PATH INHERITANCE:

DEFINING A SUBCLASS:

 A Subclass can be defined as follows:


Class subclassname extends superclassname
{
Variable declaration; Methods declaration;
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

}
 The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
 Now , the subclass contains its own variables and methods as well those of the superclass

EXAMPLE:

OUTPUT:
Parent Method
Child Method

SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.

USE OF SUPER:
Super is used to refer immediate parent class instance variable
super() is used to invoke immediate parent class constructor
super is used to invoke immediate parent class method

2. DESCRIBE IN DETAILS ABOUT INTERFACES.

INTERFACES
 An interface in java is a blueprint of a class. It has static constants and abstract methods only.
 The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body.
 It is used to achieve fully abstraction and multiple inheritances in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.

USE OF INTERFACE:

 There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

 By interface, we can support the functionality of multiple inheritances.


 It can be used to achieve loose coupling.

RELATIONSHIP BETWEEN CLASSES AND INTERFACES

As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface

CLASS INTERFACE
The members of a class can be constant or The members of an interface are always
varaibles. declared as constant, i.e., their values are final.

The class definition can contain the code for The methods in an interface are abstract
each of its methods. That is , the methods can be in nature, i.e., there is no code associated
abstract or non-abstract. with them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.

It can use various access specifiers like public, It can only use the public access specifier.
private or protected.

INTERFACE SYNTAX:
interface interfaceName
{
Variables declaration; Method declaration;
}
interface - keyword.
interfacename - any valid java variable.

SIMPLE EXAMPLE OF JAVA INTERFACE


In this example, Printable interface have only one method, its implementation is provided in the A
class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){ A6 obj = new A6();


obj.print();
}

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Output: Hello
MULTIPLE INHERITANCES IN JAVA BY INTERFACE

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){ A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:
Hello Welcome
Example 2:
Interface A
{
Void Adisplay();
Void Ashow();
}
Interface B
{
Void Bdisplay();
Void Bshow();
}
Class AB implements A,B
{
Void Adisplay();
{
System.out.println(A DISPLAY”);
}

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

Void Ashow();
{
System.out.println(A SHOW”);
}
Void Bdisplay();
{
System.out.println(B DISPLAY”);
}
Void Bshow();
{
System.out.println(B SHOW”);
}}
Class interface AB
{
Public static void main(String args[])
{
AB obj=new AB();
Obj.Adisplay();
Obj.Adshow();
Obj.Bdisplay();
Obj.Bshow();
}}

3. EXPLAIN SUPER KEYWORD IN DETAIL?


SUPER KEYWORD:
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.

USE OF SUPER:
Super is used to refer immediate parent class instance variable
super() is used to invoke immediate parent class constructor
super is used to invoke immediate parent class method

1)super is used to refer immediate parent class instance variable:


class Vehicle
{
int speed=50;
}
class Bike3 extends Vehicle
{
int speed=100; void display()
{
System.out.println(super.speed); //will print speed of Vehicle
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[])
{
Bike3 b=new Bike3(); b.display();
}
}

Programming in java Department of CSE


SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

SUPER CAN BE USED TO INVOKE PARENT CLASS METHOD:


class Person
{
void message()
{
System.out.println("welcome");
}
}
class Student extends Person
{
void message()
{
System.out.println("welcome to java");
}
void display()
{
message();//will invoke current class message() method super.message();//will invoke parent
class message() method
}
public static void main(String args[])
{
Student s=new Student(); s.display();
}
}
OUTPUT:

Welcome to java
Welcome

SUPER IS USED TO INVOKE PARENT CLASS CONSTRUCTOR

class Vehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
}
class Bike extends Vehicle
{
Bike()
{
super();//will invoke parent class constructor System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike b=new Bike();
}
}
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

OUTPUT:
Vehicle is created
Bike is created

4. EXPLAIN IN DETAIL ABOUT PACKAGES IN JAVA


 SYNOPSIS
 INTRODUCTION BENEFITS
 TYPES OF PACKAGES
 ACCESSING CLASS FROM A PACKAGE
 CREATING YOUR OWN PACKAGE DEFAULT PACKAGE
 FINDING PACKAGE
 CLASSPATH ENVIRONMENT VARIABLE
 ACCESS SPECIFIERS
 EXAMPLE
INTRODUCTION:
 Packages provide a mechanism for grouping a variety of classes and / or interfaces together.
 Grouping is based on functionality Benefits of Packages:
 The classes contained in the packages of other programs can be reused.
In packages, classes can be unique compared with classes in other packages.
A package provides a way to hide classes.
Types of packages:
• Pre-defined packages or Java API packages
• User-defined packages
Java API packages:
A large number of classes grouped into different packages based on functionality.
Examples:
 java.lang
 java.util
 java.io
 java.awt
 .java.net
 java. applet etc.
Accessing Classes in a Package:
1. Fully Qualified class name: Example:java.awt.Color
2. import packagename.classname; Example: import java.awt.Color;
or
import packagename.*; Example: import java.awt.*;
Import statement must appear at the top of the file, before any class declaration

Creating Your Own Package

1. Declare the package at the beginning of a file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory where the main
source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory

Syntax:
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

package [PackageName];
public class [ClassName]
{
//Body of the class
}

Example:
package firstPackage; public class FirstClass
{
//Body of the class
}

Example:
//Class in package package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(“Class A”);
}
}
//Importing class from package import p1.*;
class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA(); obA.displayA();
}
}

Creating Packages:
 Consider the following declaration: package firstPackage.secondPackage;
 This package is stored in subdirectory named firstPackage.secondPackage.
 A java package can contain more than one class definitions that can be declared as public.
 Only one of the classes may be declared public and that class name with .java extension is the
source file name.

Default Package:
• If a source file does not begin with the package statement, the classes contained in the source
file reside in the default package
• The java compiler automatically looks in the default package to find classes

Finding Packages:
3. By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
4. Specify a directory path using CLASSPATH environmental variable

CLASSPATH Environment Variable


• The compiler and runtime interpreter know how to find standard packages such as
java.lang and java.util
• The CLASSPATH environment variable is used to direct the compiler and interpreter to
where programmer defined imported packages can be found
• The CLASSPATH environment variable is an ordered list of directories and files
• To set the CLASSPATH variable we use the following command: set CLASSPATH=c:\
• Java compiler and interpreter searches the user defined packages from the above directory.
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

• To clear the previous setting we use: set CLASSPATH=

ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes, variables, methods and
constructor

Types of access-specifiers:

 Default - Visible to the package, the default.


 Private - Visible to the class only.
 Public - Visible to the world.
 Protected -Visible to the package and all subclasses.

Levels of Access Control:

public protected friendly (default) private

same class Yes Yes Yes Yes

Subclass in Yes Yes Yes No


the same
package

Other class Yes Yes Yes No


in the
same package

Subclass in Yes Yes No No


other
packages
Non- subclass Yes No No No
in other
package

Example 1:
package my_package;
class A // package scope
{
// A’s public & private members
}
public class B // public scope
{
// B’s public and private members
}

Example 2:
package my_package;
class A
{
Programming in java Department of CSE
SRI MANAKULA VINAYAGAR ENGINEERING COLLEGE

int get() { return data; } // package scope


public A(int d) { data=d;} // public scope
private int data; // private scope
}
class B
{
void f()
{
A a=new A(d);// OK A has package scope
int d=a.get(); // OK – get() has package scope
int d1=a.data;// Error! – data is private
}
}

Programming in java Department of CSE

You might also like