Unit II Java
Unit II Java
Unit: II
Basic concepts, member access rules, usage of super key word, forms of inheritance, method overriding, abstract classes,
dynamic method dispatch, using final with inheritance, the Object class. Defining, Creating and Accessing a Package,
Understanding CLASSPATH, importing packages, differences between classes and interfaces, defining an interface,
implementing interface, applying interfaces, variables in interface and extending interfaces.
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;
package xyzpackage;
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.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.
Example:
In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class extends class
Addition and the protected modifier allows the access of protected members in subclasses (in any
packages).
Addition.java
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
4. Public access modifier
The members, methods and classes that are declared public can be accessed from anywhere.
This modifier doesn’t put any restriction on the access.
Example:
The method addTwoNumbers() has public modifier and class Test is able to access this method without
even extending the Addition class. This is because public modifier has visibility everywhere.
Addition.java
package abcpackage;
Test.java
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
The scope of access modifiers in tabular form
2.2.1. Use of super with variables: This is used when a derived class and base class has same data
members. In that case there is a possibility of ambiguity for the JVM.
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:
MaximumSpeed:180
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could access
maxSpeed of base class in sublcass using super keyword.
2.2.2. Use of super with methods:
This is used when we want to call parent class method. So whenever a parent and child class have same
named methods then to resolve ambiguity we use super keyword.
class Person
{
void message()
{
System.out.println("This is person class");
}
}
class Test
{
public static void main(String args[])
{
Student s = new Student();
Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of super keyword, message() of superclass could also be invoked.
2.2.3. Use of super with constructors:
The super keyword can also be used to access the parent class constructor.
The’super’ can call both parametric as well as non parametric constructors depending upon the
situation.
The call to super( ) must be the first statement in derived class constructor.
If a subclass constructor invokes a constructor of its super class , either explicitly or implicitly ,
they are called in chain method.
class Person
{
Person( )
{
System.out.println("Person class Constructor");
}
}
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another class.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Need of Inheritance:
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
2.3.1.1 Single Inheritance : In single inheritance, subclasses inherit the features of one superclass.
import java.io.*;
import java.util.Scanner;
class Student
{
int regno;
int year;
String name;
public void method( )
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter student name:");
name=ob.nextLine();
System.out.print("Enter register number:");
regno=ob.nextInt();
System.out.print("Enter year:");
year=ob.nextInt();
}
}
public void display()
{
System.out.println("\t\t\t *****STUDENT DETAILS*****");
System.out.println("Name :"+name);
System.out.println("Register number:"+regno);
System.out.println("Year:"+year);
System.out.println("Total Marks Obtained :"+tot);
}
public static void main(String[] arg)
{
Marks s=new Marks();
s.method();
s.method2();
s.display();
}
}
Output:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class. In below image, the class A serves as a base class
for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.
import java.io.*;
import java.util.Scanner;
class Student
{
int regno;
int year;
String name;
public void method( )
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter student name:");
name=ob.nextLine();
System.out.print("Enter register number:");
regno=ob.nextInt();
System.out.print("Enter year:");
year=ob.nextInt();
}
}
class Marks extends Student
{
int arr[]=new int[5],tot;
public void method2()
{
Scanner ob = new Scanner(System.in);
System.out.print("Enter Student marks : ");
for (int i=0;i<5;i++)
{
arr[i]=ob.nextInt();
tot = tot + arr[i];
}
}
class Helper
{
public static void main(String[] arg)
{
Extra s=new Extra();
s.method();
s.method2();
s.method3( );
s.display();
}
}
2.3.1.3 Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base
class) for more than one sub class. The class A serves as a base class for the derived class B,C and D.
import java.util.*;
class Student
{
String name,dob,mailid;
long phno;
void getdata()
{
Scanner inp=new Scanner(System.in);
System.out.println("Enter the name:");
name=inp.next();
System.out.println("Enter the Date of Birth:");
dob=inp.next();
System.out.println("Enter the mail id:");
mailid=inp.next();
}
}
class UGadmission extends Student
{
float m1,m2;
String schname;
void get()
{
Scanner inp=new Scanner(System.in);
System.out.println("Enter the 12th mark:");
m1=inp.nextFloat();
System.out.println("Enter the CGPA:");
cgpa=inp.nextFloat();
System.out.println("Enter the college name:");
collegename=inp.next();
}
void display()
{
System.out.println("Name:"+name);
System.out.println("Date of Birth:"+dob);
System.out.println("Phone no:"+phno);
System.out.println("Mail id:"+mailid);
SMVEC-Department of Information Technology Page 12
IT T45- Java Programming
System.out.println("12th mark:"+m1);
System.out.println("CGPA:"+cgpa);
System.out.println("College name:"+collegename);
}
}
class Hierarchicalinheritance
{
public static void main(String[]args)
{
UGadmission ob1=new UGadmission();
ob1.getdata();
ob1.get();
ob1.display();
PGadmission ob2=new PGadmission();
ob2.getdata();
ob2.get();
ob2.display();
}
}
Overriding is a feature that allows a subclass or child class to provide a specific implementation of a
method that is already provided by one of its super-classes or parent classes.
The overriding method must have same return type (or subtype)
Method Hiding:
It is defined as defining a static method with the same signature as in base class in the derived
class is known as method hiding.
Example for Method Overriding:
class Shape
{
void draw()
{
System.out.println(“Drawing basic shapes”);
}
}
class Circle extends Shape
{
void draw()
{
int r=5;
System.out.println(“Drawing a circle”);
int area= r*r;
System.out.println(“Area of circle”+area);
}
}
class Rectangle extends Shape
{
void draw()
{
int len=10,b=20;
System.out.println(“Drawing aRectangle”);
int area= len*b;
System.out.println(“Area of Rectangle”+area);
}
}
class Helper
{
public static void main(String[]args)
{
Shape s = new Shape();
s.draw();
Circle c= new Circle();
c.draw();
Rectangle r = new Rectangle();
r.draw();
}
}
Abstraction: It is the way of hiding the implementation and showing only the functionality to
the user. There are two ways to achieve abstraction:
Abstract class
Interfaces
Abstract Class: A class which is declared with the abstract keyword is known as abstract class
in java. The abstract class can have
Abstract Methods
Concrete methods - Non abstract methods
class Test
{
public static void main(String[]args)
{
Developer d = new Developer( );
d.details( );
d.getsalary( );
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.
class Bank
{
void interest( )
{
System.out.println(“ Interest rate calculation”);
}
}
}
}
Output:
Interest rate calculation
Interest rate for ABC Bank 8%
Interest rate for XYZ Bank 10%
Note: It is not necessary to declare final methods in the initial stage of inheritance(base class
always). We can declare final method in any subclass for which we want that if any other class
extends this subclass, then it must follow same implementation of the method as in the that
subclass.
Example:
class XYZ
{
final void demo( )
{
System.out.println("XYZ Class Method");
}
}
The above program would throw a compilation error, however we can use the parent class final method
in sub class without any issues. This program would run fine as we are not overriding the final method.
That shows that final methods are inherited but they are not eligible for overriding.
void run()
honda.run();
Constructor of Object:
Object ( )
toString() : It provides String representation of an Object and used to convert an object to String.
hashCode( ) For every object, JVM generates a unique number which is hash code. It returns distinct
integers for distinct objects. Returns a hash value that is used to search object in a collection.
JVM(Java Virtual Machine) uses hashcode method while saving objects into hashing related data
structures like HashSet, HashMap, Hashtable etc. The main advantage of saving objects based on hash
code is that searching becomes easy.
equals(Object obj) : Compares the given object to “this” object (the object on which the method is
called).
getClass() : Returns the class object of “this” object and used to get actual runtime class of the object.
Example:
public class Test
{
public static void main(String[] args)
{
Object obj = new String("Hello");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "+ c.getName());
}
}
Output:
Class of Object obj is : java.lang.String
finalize() method : This method is called just before an object is garbage collected. It is called by
the Garbage Collector on an object when garbage collector determines that there are no more references
to the object.
clone() : It returns a new object that is exactly the same as this object. For clone() method refer Clone()
wait(), notify() notifyAll() are related to Concurrency. wait ( )- causes the current thread to wait for the
specified milliseconds and nanoseconds, notify( )-until another thread notifies wakes up single thread,
waiting on this object's monitor .notifyall ( )- wakes up all the threads, waiting on this object's monitor.
Java language has a rich set of built in API packages from which we can access interfaces and classes,
and then fields, constructors, and methods.
Package Description
java.applet Package that enables the creation of applets through the Applet
class. It also provides several interfaces that connect an applet to
. its document and to resources for playing audio
The Java Package name consists of words separated by periods. The first part of the name
contains the name java. The remaining words of the Java Package name reflect the contents of the
package. The Java Package name also reflects its directory structure. For example the statement
java.awt
This statement uses a fully qualified name Math to invoke the method sqrt( ).The methods begin with
lower case letters
import java.util.Date;
System.out.println(date.toString());
Output
on Mar 04 09:51:52 CDT 2018
We can create our own package and use it in our programs. Creation of package in java is easy.
We must first declare the name of the package using the package keyword followed by a
package name. This must be the first statement in a Java source file (except for comments and
white spaces).
Steps involved in creation of Package:
1. Declare the name of the package with package keyword. This must be the first statement in Java
source file.
package packagename;
2. The second step is to define classes and interfaces and put it inside the package. A package can
contain any number of classes; however one of the classes should have the public access specifier.
For example
package mypack
public class sample
{
//body of the class
}
3. Import the package in the other class by
import packagename.classname;
4. Compile the package program
>javac Calculate.java
>javac -d .. Calculate.java
Which creates a folder with the class file of the package in the root directory
Example :
Creating a Package:
package mypack;
public class Calculate
{
public void add(int a,int b)
{
System.out.println("Addition:"+(a+b));
}
public void sub(int a,int b)
{
System.out.println("Subtraction:"+(a-b));
}
}
import mypack.Calculate;
import java.util.*;
class Compute
{
public static void main(String[]args)
{
int a,b;
Scanner inp=new Scanner(System.in);
System.out.println("Enter 2 input values:");
a=inp.nextInt();
b=inp.nextInt();
Calculate ob=new Calculate();
ob.add(a,b);
ob.sub(a,b);
}
}
Output:
>javac Calculate.java
>javac -d . Calculate.java
>javac Compute.java
>java Compute
It is actually an environment variable in Java and tells the Java applications and JVM where to find the
libraries of classes.These included both the predefined and user defined packages(libraries)
It is a global system variable accessible by the computer operating ,other variables that are in
the environment variable are : computer name and user name.
In Java CLASSPATH holds the list of Java class file directories and the JAR(Java Archive files)which
is delivered class library file.
When a standalone Java program is trying to run, we have to change the class path variable
when the program start executes the Java’s runtime system is called.
Interpreter runs through the code , if it reads the class name, it will look at each directory listed
in the CLASSPATH variable, if it does not find the class name it displays error.
Extension classes: classes bundled as JAR files snd kept in the $JAVA_HOME/jre/lib/ext
User classes: The class is located via -classpath or -cp command line option or CLASSPATH
environment variables
2.11 Interfaces :
To reduce the complexity and simplify the language, multiple inheritances are not supported in
java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be ambiguity
to call the method of A or B class.
Syntax :
interface <interface_name>
// by default.
To declare an interface, use interface keyword. It is used to provide total abstraction. That means all
the methods in interface are declared with empty body and are public and all fields are public, static and
final by default. A class that implement interface must implement all the methods declared in the
interface. To implement interface use implements keyword.
// A simple interface
interface Player
{
final int id = 10;
int move()
}
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value
of the variable must be assigned in a static context in which no instance exists. The final modifier
ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by
program code.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
Example
// Filename: Sports.java
// Filename: Football.java
// Filename: Hockey.java
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to
define the three methods from Football and the two methods from Sports.
BASIS FOR
CLASS INTERFACE
COMPARISON
Access specifier The members of a class can The members of an interface are always
be private, public or public.
protected.
Methods The methods of a class are The methods in an interface are purely
defined to perform a abstract.
specific action.
Two Marks
1. List out the various Java Access Modifiers (or) access specifiers
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another class. Inheritance represents the IS-A relationship which
is also known as a parent-child relationship.
Need of Inheritance:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
5. List the various Types of Inheritance in Java (or) Forms of Inheritance in java
Single Inheritance
Multiple Inheritance (Through Interface)
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance (Through Interface)
6. Define Method Overriding (or) How run time polymorphism is achieved in Java
Overriding is a feature that allows a subclass or child class to provide a specific implementation
of a method that is already provided by one of its super-classes or parent classes. It achieves
run time polymorphism.
Protected instance method in superclass can be made public in sub class ,but not as private in
sub class
The final methods cannot be overridden
The static methods cannot be overridden, because static methods are bound to certain class.
We can not override constructor as parent and child class can never have constructor with same
name
The overriding method must have same return type (or subtype)
Method overloading is used to increase Method overriding is used to provide the specific
the readability of the program. implementation of the method that is already
provided by its super class.
Method overloading is performed within Method overriding occurs in two classes that have
class. IS-A (inheritance) relationship.
Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.
In java, method overloading can't be Return type must be same or covariant in method
performed by changing return type of the overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
No objects can be created for the abstract class. i.e it cannot be instantiated
it can have constructors and static methods
It can have final methods.
The sub class derived from the abstract class must either implement all the abstract methods.
BASIS FOR
CLASS INTERFACE
COMPARISON
Access specifier The members of a class can The members of an interface are always
be private, public or public.
protected.
Methods The methods of a class are The methods in an interface are purely
defined to perform a abstract.
specific action.
BASIS FOR
CLASS INTERFACE
COMPARISON
Syntax :
interface <interface_name> {
// declare constant fields
// declare methods that abstract
}
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.