UNIT-II
UNIT-II
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.
IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve
inheritance.
Now based on the above example, In Object Oriented terms following are true:
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for
the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:
public class Dog extends Mammal{
true
true
true
Since we have a good understanding of the extends keyword let us look into how the implementskeyword is used
to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the
classes.
Example:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually
an Animal
interface Animal{}
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing.
This relationship helps to reduce duplication of code as well as bugs.
This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code
that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple
applications.
In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve
this, the Van class hides the implementation details from the users of the Van class. SO basically what happens is
the users would ask the Van class to do a certain action and the Vann class will either do the work by itself or ask
another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot
extend more than one class. Therefore following is illegal:
However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple
inheritance
1. POLYMORPHISM
Polymorphism literally means taking more than one form .polymorphism is a characteristic of being able to assign a
different behavior or value in a subclass,to something that was declared in a parent class.
Types of polymorphism:
Dynamic method dispatch is important because this is how java implements run time polymorphism.
When an overridden method is called through a super class reference JVM determines which version of that
method is to be executed based on the type of object being referred at the time, the call occurs.
In other words, it is the type of object being referred to, determines which version of overridden method will be
executed.
class A
{
void show()
{
System.out.println("Inside class A");
}
}
class B extends A
{
void show()
{
System.out.println("Inside class B");
}
}
class C extends A
{
void show()
{
System.out.println("Inside class C");
}
}
class dynamicpoly
{
public static void main(String s[])
{
A a1=new A();
a1.show();
A a2;
B b1=new B();
a2=b1;
a2.show();
C c1=new C();
a2=c1;
a2.show();
c1.show();
}
}
2. “super” keyword
⮚ The super is a keyword defined in the java programming language. Keywords are basically reserved
words which have specific meaning relevant to a compiler in java programming language likewise the
super keyword indicates the following :
-- The super keyword in java programming language refers to the super class of the class where the
super keyword is currently being used.
-- The super keyword as a standalone statement is used to call the constructor of the super class in
the base class.
class one
{
int i;
one(int i)
{
this.i=i;
}
}
class two extends one
{
int i;
two(int a,int b)
{
super(a);
i=b;
}
void show()
{
System.out.println("subclass var. = "+i);
System.out.println("super class var. = "+super.i);
}
}
class superdemo1
{
public static void main(String[] args)
{
two t = new two(10,20);
t.show();
}
}
class one
{
one()
{
System.out.println("one");
}
}
class two extends one
{
two()
{
System.out.println("two");
}
}
class superdemo
{
public static void main(String[] args)
{
two t = new two();
}
}
3. “this” keyword
The this keyword helps in removing the ambiguity of references and allows to refer to the current instance within
the running program.
-- key word this is used with variables as "this.variable" and specifies the number of member variable of this
instance of that class.
class sample
{
int x;
sample()
{
this(55);
this.access();
}
sample(int x)
{
this.x=x;
}
void access()
{
System.out.println("x = "+x);
}
}
class thisdemo
{
public static void main(String[] args)
{
sample s = new sample();
}
}
4. “final” keyword
The keyword “final” means once created the property of that particular entity cannot be changed that is:
⮚ Final variables cannot be re-assigned with values
⮚ Final methods cannot be overridden
⮚ Final classes cannot be extended.
class finalvariable
{
public static void main(String[] args)
{
int x=100;
final int y=200;
x=500;
y=800;
System.out.println(x+" "+y);
}
}
Output
Output
5. Abstract method and Abstract class
⮚ 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.
⮚ There are situations in which you will want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method.
⮚ That is, sometimes you will want to create a superclass that only defines a generalized form that will
be shared by all of its subclasses, leaving it to each subclass to fill in the details.
⮚ Such a class determines the nature of the methods that the subclasses must implement.
⮚ One way this situation can occur is when a superclass is unable to create a meaningful
implementation for a method.
⮚ Abstract class
⮚ Interface
o A class that is declared as abstract is known as abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.
o A method that is declared as abstract and does not have implementation is known as abstract method.
o If there is any abstract method in the class then that class is known as abstract class
The abstract keyword is also used to declare a method as abstract. An abstract method consists of a method
signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:
void opentank()
{
System.out.println("fill the tank");
}
abstract void steering();
abstract void breaking();
}
class maruti extends car
{
maruti(int r)
{
super(r);
}
void steering()
{
System.out.println("maruti car");
}
void breaking()
{
System.out.println("apply breaks to maruti");
}
}
void breaking()
{
System.out.println("apply breaks to swift");
}
}
class drive
{
public static void main(String[] args)
{
maruti m = new maruti(100);
swift s = new swift(200);
car ref;
ref = m;
ref.opentank();
ref.steering();
ref.breaking();
ref = s;
ref.opentank();
ref.steering();
ref.breaking();
}
}
6. INTERFACE IN JAVA
Java doesn’t support multiple inheritance
⮚ Reason is, in java one sub class should have only one super class.
⮚ But in the case of multiple inheritance this rule is violated as in multiple inheritance we have one sub
class and more than one super classes.
⮚ Hence java does not directly support multiple inheritance but implements it using the interface
concept.
⮚ Consider the following figure to understand the problem that arises in case of multiple inheritance.
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A
class describes the attributes and behaviors of an object. 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.
o Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that
matches the package name.
Declaring Interfaces:
interface interface_name
{
Method declarations
}
interface aicte
{
void recognition();
}
interface EnggCollege
{
void syllabus();
void strength();
}
interface OU extends EnggCollege
{
void labs();
}
class A implements aicte, EnggCollege
{
public void recognition()
{
System.out.println("This college has been recognised by aicte");
}
public void syllabus()
{
System.out.println("Syllabus: 6 subjects for every sem");
}
public void strength()
{
System.out.println("Minimum strength of College must be 60");
}
}
class B implements aicte, OU
{
public void recognition()
{
System.out.println("This college has been recognised by aicte");
}
public void labs()
{
System.out.println("Labs facility is present in this college");
}
public void syllabus()
{
System.out.println("Syllabus: 6 subjects for every sem");
}
public void strength()
{
System.out.println("Minimum strength of College must be 60");
}
}
class interfacedemo
{
public static void main(String args[])
{
A a = new A();
B b = new B();
System.out.println("For class A:");
a.recognition();
a.syllabus();
a.strength();
System.out.println("For class B:");
b.recognition();
b.labs();
b.syllabus();
b.strength();
}
}
• To create a package, First we have to create a directory /directory structure that matches the package
hierarchy.
• To make a class belongs to a particular package include the package statement as the first statement of
source file.
Examples:
• Library packages are automatically imported irrespective of the location of compiling and executing
program
environment variable
• Most ideal location for compiling/executing a program is immediately above the package structure.
Defining a Package
To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored. If you omit the package statement, the class
names are put into the default package, which has no name. (This is why you haven’t had to worry about packages
before now.) While the default package is fine for short, sample programs, it is inadequate for real applications.
Most of the time, you will define a package for your code.
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any classes you declare to be
part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the
directory name must match the package name exactly.
More than one file can include the same package statement. The package statement simply specifies to which
package the classes defined in a file belong. It does not exclude other classes in other files from being part of that
same package. Most real-world packages are spread across many files.
You can create a hierarchy of packages. To do so, simply separate each package
name from the one above it by use of a period.
Package pkg1[.pkg2[.pkg3]];
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we
will learn access modifiers.
subtraction.java
package p1;
public class subtraction
{
int x,y,z;
public subtraction(int a,int b)
{
x=a;
y=b;
}
public void sub()
{
z=x-y;
System.out.println("difference="+z);
}
}
multiplication.java
package p1;
public class multiplication
{
int x,y,z;
public multiplication(int a,int b)
{
x=a;
y=b;
}
public void multiply()
{
z=x*y;
System.out.println("product="+z);
}
}
packagedemo.java
import p1.addition;
import p1.subtraction;
import p1.multiplication;
public class packagedemo
{
public static void main(String args[])
{
Output:
A.java
package access;
public class A
{
int p=10;
private int q=20;
public int r=30;
protected int s=40;
}
If
System.out.println(y.p);
System.out.println(y.q); are commented in the above the program then: