Unit-Ii Java R20
Unit-Ii Java R20
extends Keyword:
Sample Code
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.
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[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default. To access the
parent property, we need to use super keyword.
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.
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...
In the above example Animal and Dog both classes have eat() method
if we call eat() method from Dog class, it will call the eat() method of Dog class by
default because priority is given to local.
The super keyword can also be used to invoke the parent class constructor. Let's
see a simple 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
Note: super() is added in each class constructor automatically by compiler if there is no super() or
this().
Multilevel Hierarchy in java programming
In simple inheritance a subclass or derived class derives the properties from its
parent class, but in multilevel inheritance a subclass is derived from a derived class.
One class inherits only single class. Therefore, in multilevel inheritance, every time
ladder increases by one. The lower most class will have the properties of all the
super classes’.
It is common that a class is derived from another derived class. The class student
serves as a base class for the derived class marks, which in turn serves as a base
class for the derived class percentage. The class marks is known as intermediates
base class since it provides a link for the inheritance between student and
percentage.
The chain is known as inheritance path. When this type of situation occurs, each
subclass inherits all of the features found in all of its super classes. In this case,
percentage inherits all aspects of marks and student.
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
Output
G:\>javac Multi_Inhe.java
G:\>java Multi_Inhe
Rollno = 102689
Name = srilakshmi
Total = 350
Percentage = 70
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
Let's understand the problem that we may face in the program if we don't use
method overriding.
Output:
Vehicle is running
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.
Consider a scenario where Bank is a class that provides functionality to get the rate
of interest. However, the rate of interest varies according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.
Dynamic method dispatch or Runtime Polymorphism :
Upcasting:
When Parent class reference variable refers to Child class object, it is known
as Upcasting
Example
class Game
{
System.out.println("outdoor game");
gm.type();
ck.type();
Output:
Outdoor game
Outdoor game
Static binding in Java occurs during compile time while dynamic binding occurs
during runtime. Static binding uses type(Class) information for binding while
dynamic binding uses instance of class(Object) to resolve calling of method at run-
time. Overloaded methods are bonded using static binding while overridden
methods are bonded using dynamic binding at runtime.
In simpler terms, Static binding means when the type of object which is invoking
the method is determined at compile time by the compiler. While Dynamic binding
means when the type of object which is invoking the method is determined at run
time by the compiler.
Abstract class in Java :
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).
Before learning the Java abstract class, let's understand the abstraction in Java
first.
Abstraction in Java :
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you 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.
2. Interface (100%)
Points to Remember :
o It can have final methods which will force the subclass not to change the
body of the method.
A method which is declared as abstract and does not have implementation is known
as an abstract method.
In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely
final is a keyword in java used for restricting some functionalities. We can declare
variables, methods and classes with final keyword.
EX2:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
When a class is declared as final then it cannot be subclassed i.e. no any other
class can extend it. This is particularly useful, for example, when creating an
immutable class like the predefined String class. The following fragment
illustrates final keyword with a class:
final class A
Note :
Declaring a class as final implicitly declares all of its methods as final, too.
It is illegal to declare a class as both abstract and final since an abstract
class is incomplete by itself and relies upon its subclasses to provide complete
implementations. For more on abstract classes, refer abstract classes 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.
Let's take an example, there is getObject() method that returns an object but it can
be of any type like Employee,Student etc, we can use Object class reference to
refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object
can be compared, object can be cloned, object can be notified etc.
Methods of Object class:
Method Description
public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this
CloneNotSupportedException object.
public final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long causes the current thread to wait for the specified
timeout)throws InterruptedException milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait(long timeout,int causes the current thread to wait for the specified
nanos)throws InterruptedException milliseconds and nanoseconds, until another thread
notifies (invokes notify() or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).
Java Package :
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in
case of windows) etc. If you want to keep the package within the same
directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the
class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents de
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use 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.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
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.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello
If you import a package, all the classes and interface of that package will be
imported excluding the classes and interfaces of the subpackages. Hence,
you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Set CLASSPATH System Variable
To display the current CLASSPATH variable, use the following commands in Windows
In this example we have two classes, Test class is trying to access the default
method of Addition class, since class Test belongs to a different package, this
program would throw compilation error, because the scope of default modifier is
limited to the same package in which it is declared.
Addition.java
package abcpackage;
Test.java
package xyzpackage;
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
obj.addTwoNumbers(10, 21);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)
1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that
class from outside of the class.
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:
package abcpackage;
public class Addition {
package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
Output:
33
package abcpackage;
package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
System.out.println(obj.addTwoNumbers(100, 1));
}
}
Output:
101
Lets see the scope of these access modifiers in tabular form:
Interface in Java:
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
There are mainly three reasons to use interface. They are given below.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Java 8 Interface Improvement
Since Java 8, interface can have default and static methods which is
discussed later.
In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
In this example, the Drawable interface has only one method. Its
implementation is provided by Rectangle and Circle classes. In a real
scenario, an interface is defined by someone else, but its implementation is
provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the
interface.
File: TestInterface1.java
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output: Hello
Welcome
Since Java 8, we can have method body in interface. But we need to make it
default method. Let's see an example:
File: TestInterfaceDefault.java
1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}
Output:
drawing rectangle
default method
Since Java 8, we can have static method in interface. Let's see an example:
File: TestInterfaceStatic.java
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}
Output:
drawing rectangle
27
Abstract class and interface both are used to achieve abstraction where we
can declare the abstract methods. Abstract class and interface both can't be
instantiated.
But there are many differences between abstract class and interface that are
given below.
1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods. Since Java
8, it can have default and
static methods also.
3) Abstract class can have final, non- Interface has only static and
final, static and non-static variables. final variables.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
interface interface_name{
...
interface nested_interface_name{
...
}
}
EXAMPLE1:
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}
Multiple Interfaces:
To implement multiple interfaces, separate them with a comma:
Example:
interface FirstInterface {
interface SecondInterface {
System.out.println("Some text..");
class MyMainClass {
myObj.myMethod();
myObj.myOtherMethod();
Output:
Some text...
Some other text..