Java UNIT-2
Java UNIT-2
Inheritance
Inheritance: Creating new class from existing class such that the features of existing class are
available to the new class is called inheritance Already existing class is called super class &
produced class is called sub class Using inheritance while creating sub classes a programmer
can reuse the super class code without rewriting it
Syntax: class subclass_name extends superclass_name
eg: class Child extends Parent
Program 1: Write a program to create a Person class which contains general details of a
person and create a sub class Employ which contains company details of a person Reuse the
general details of the person in its sub class Inheritance Example
class Person
{
String name;
String permanentAddress;
int age;
void set_PermanentDetails (String name, String permanentAddress, int age)
{
this.name = name;
this.permanentAddress = permanentAddress;
this.age = age;
}
void get_PermanentDetails ()
{
System.out.println ("Name : " + name);
System.out.println("PermanentAddress:"+ permanentAddress);
System.out.println ("Age :" + age);
}
}
class Employ extends Person
{
int id;
String companyName;
String companyAddress;
Employ (int id, String name, String permanentAddress, int age,
String companyName, String companyAddress)
{
this.id = id;
set_PermanentDetails (name, permanentAddress, age);
this.companyName = companyName;
this.companyAddress = companyAddress;
}
void get_EmployDetails ()
{
System.out.println ("Employ Id : " + id);
get_PermanentDetails ();
System.out.println ("Company Name : "+ companyName);
System.out.println ("Company Address : "+companyAddress);
}
}
class InherDemo
{
public static void main (String args [])
{
Employ e1 = new Employ (101, "Suresh Kumar", "18-Madhura Nagar-Tirupati", 29,
"Centris Software- Chennai", "20-RVS Nagar");
e1.get_EmployDetails ();
}
}
Output:
Program 2: Write a program to illustrate the order of calling of default constructor in super
and sub class
Default constructors in super and sub class
class One
{ One ( ) //super class default constructor
{
System.out.println ("Super class default constructor called");
}
}
class Two extends One
{ Two ( ) //sub class default constructor
{
System.out.println ("Sub class default constructor called");
}
}
class Const
{
public static void main (String args[])
{
Two t=new Two ( ); //create sub class object
}
}
Output:
Super class default constructor is available to sub class by default First super class default
constructor is executed then sub class default constructor is executed. Super class
parameterized constructor is not automatically available to subclass super is the key word
that refers to super class
Program 3: Write a program to access the super class method, super class parameterized
constructor and super class instance variable by using super keyword from sub class super
refers to super class- constructors, instance variables and methods
class A
{
int x;
A (int x)
{
this.x = x;
}
void show( )
{
System.out.println("super class method: x = "+x);
}
}
class B extends A
{
int y;
B (int a,int b)
{
super(a) ; // (or) x=a;
y=b;
}
void show( )
{
super.show ();
System.out.println ("y = "+y);
System.out.println (“ super x = “ + super.x);
}
}
class SuperUse
{
public static void main(String args[])
{
B ob = new B (10, 24);
ob.show ( );
}
}
Output:
Types of inheritance:
Single Inheritance:
In Single Inheritance one class extends another class (one class only).
In above diagram, Class B extends only Class A. Class A is a super class and Class B is a
Sub-class.
Multiple Inheritance:
In Multiple Inheritance, one class extending more than one class. Java does not support
multiple inheritance
Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.
Hybrid Inheritance:
Hybrid inheritance is a combination of Single and Multiple inheritance. As per above
example, all the public and protected members of Class A are inherited into Class D, first via
Class B and secondly via Class C
Polymorphism
Polymorphism came from the two Greek words “poly” means many and “morphos” means
forms If the same method has ability to take more than one form to perform several tasks then
it is called polymorphism It is of two types: Dynamic polymorphism and Static polymorphism
Method Overloading: Writing two or more methods with the same name, but with a
difference in the method signatures is called method over loading Method signature
represents the method name along with the method parameters In method over loading JVM
understands which method is called depending upon the difference in the method signature
The difference may be due to the following:
There is a difference in the no of parameters
void add (int a,int b)
void add (int a,int b,int c)
There is a difference in the data types of parameters
void add (int a,float b)
void add (double a,double b)
There is a difference in the sequence of parameters
void swap (int a,char b)
void swap (char a,int b)
Program 1: Write a program to create a class which contains two methods with the same
name but with different signatures overloading of methods---------Dynamic polymorphism
class Sample
{
void add(int a,int b)
{
System.out.println ("sum of two="+ (a+b));
}
void add(int a,int b,int c)
{
System.out.println ("sum of three="+ (a+b+c));
}
}
class OverLoad
{
public static void main(String[] args)
{
Sample s=new Sample ( );
s.add(20, 25);
s.add (20, 25, 30);
}
}
Output:
Method Overriding: Writing two or more methods in super & sub classes with same name
and same signatures is called method overriding In method overriding JVM executes a
method depending on the type of the object
Program 2: Write a program that contains a super and sub class which contains a method
with same name and same method signature, behavior of the method is dynamically decided
//overriding of methods ----------------------------- Dynamic polymorphism
class Animal
{
void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
System.out.println ("Dogs can walk and run");
}
}
public class OverRide
{
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
}
}
Output:
Achieving method overloading & method overriding using instance methods is an example of
dynamic polymorphism
Static Polymorphism: The polymorphism exhibited at compile time is called Static
polymorphism Here the compiler knows which method is called at the compilation This is
also called compile time polymorphism or static binding Achieving method overloading &
method overriding using private, static and final methods is an example of Static
Polymorphism
Program 3: Write a program to illustrate static polymorphism
//Static Polymorphism
class Animal
{
static void move ()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{
static void move ()
{
System.out.println ("Dogs can walk and run");
}
}
public class StaticPoly
{
public static void main(String args[])
{
Animalmove();
Dogmove ();
}
}
Output:
A method with method body is called concrete method In general any class will have all
concrete methods A method without method body is called abstract method A class that
contains abstract method is called abstract class It is possible to implement the abstract
methods differently in the subclasses of an abstract class These different implementations will
help the programmer to perform different tasks depending on the need of the sub classes
Moreover, the common members of the abstract class are also shared by the sub classes
The abstract methods and abstract class should be declared using the keyword abstract
We cannot create objects to abstract class because it is having incomplete code Whenever an
abstract class is created, subclass should be created to it and the abstract methods should be
implemented in the subclasses, then we can create objects to the subclasses
➢ An abstract class is a class with zero or more abstract methods
➢ An abstract class contains instance variables & concrete methods in addition to abstract
methods
➢ It is not possible to create objects to abstract class But we can create a reference of
abstract class type
➢ All the abstract methods of the abstract class should be implemented in its sub classes If
any method is not implemented, then that sub class should be declared as “abstract”
Abstract class reference can be used to refer to the objects of its sub classes
➢ Abstract class references cannot refer to the individual methods of sub
classes A class cannot be both “abstract” & “final”
eg: final abstract class A // invalid
Program 1: Write an example program for abstract class Using abstract methods and classes
abstract class Figure
{
double dim1;
double dim2;
{
dim1 = a;
dim2 = b;
}
abstract double area ();
// area is now an abstract method
}
class Rectangle extends Figure
{
Rectangle (double a, double b)
{
super (a, b);
}
double area () // override area for rectangle
{
System.out.println ("Inside Area of Rectangle");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle (double a, double b)
{
super (a, b);
}
double area() // override area for right triangle
{
System.out.println ("Inside Area of Triangle");
return dim1 * dim2 / 2;
}
}
class AbstractAreas
{
public static void main(String args[])
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8);
System.out.println("Area is " + rarea()); System.out.println("Area is "+ t.area());
}
}
Output:
Interface
A programmer uses an abstract class when there are some common features shared by all the
objects A programmer writes an interface when all the features have different implementations
for different objects Interfaces are written when the programmer wants to leave the
implementation to third party vendors An interface is a specification of method prototypes All
the methods in an interface are abstract methods
➢ An interface is a specification of method prototypes
➢ An interface contains zero or more abstract methods
➢ All the methods of interface are public, abstract by default
➢ An interface may contain variables which are by default public static final
➢ Once an interface is written any third party vendor can implement it
➢ All the methods of the interface should be implemented in its implementation classes
➢ If any one of the method is not implemented, then that implementation class should be
declared as abstract
➢ We cannot create an object to an interface
➢ We can create a reference variable to an interface
➢ An interface cannot implement another interface
➢ An interface can extend another interface
➢ A class can implement multiple interfaces
Java does not support multiple inheritance But multiple inheritance can be achieved by using
interfaces
Program 2: Write a program to illustrate how to achieve multiple inheritance using multiple
interfaces
//interface Demo
interface Father
{
double PROPERTY = 10000;
double HEIGHT = 56;
}
interface Mother
{
double PROPERTY = 30000;
double HEIGHT = 54;
}
class MyClass implements Father, Mother
{
void show()
{
System.out.println("Total property is :" +(FatherPROPERTY+MotherPROPERTY));
System.out.println ("Average height is :" + (FatherHEIGHT + MotherHEIGHT)/2 );
}
}
class InterfaceDemo
{
public static void main(String args[])
{
MyClass ob1 = new MyClass();
ob1.show();
}
}
Output:
Packages
A package is a container of classes and interfaces A package represents a directory that
contains related group of classes and interfaces For example, when we write statemens like:
import javaio*;
Here we are importing classes of javaio package Here, java is a directory name and io is
another sub directory within it The „*‟ represents all the classes and interfaces of that io sub
directory We can create our own packages called user-defined packages or extend the
available packages User-defined packages can also be imported into other classes and used
exactly in the same way as the Built-in packages Packages provide reusability
Program 3: Write a program to add one more class Subtraction to the same package pack
//Adding one more class to package pack:
package pack;
public class Subtraction
{
private double d1,d2;
public Subtraction(double a, double b)
{
d1 = a;
d2 =b;
}
public void difference()
{
System.out.println ("Sum of two given numbers is : " + (d1 - d2) );
}
}
Compiling the above program:
Program 4: Write a program to access all the classes in the package pack
//To import all the classes and interfaces in a class using import pack*;
import pack*;
class Use
{
public static void main(String args[])
{
Addition ob1 = new Addition(105,206);
ob1.sum();
Subtraction ob2 = new Subtraction(302,4011);
ob2.difference();
}
}
In this case, please be sure that any of the Additionjava and Subtractionjava programs will not
exist in the current directory Delete them from the current directory as they cause confusion
for the Java compiler The compiler looks for byte code in Additionjava and Subtractionjava
files and there it gets no byte code and hence it flags some errors
Output:
If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import If our package exists in e:\sub then we need to set class path as
follows:
We are setting the classpath to e:\sub directory and current directory () and
%CLASSPATH% means retain the already available classpath as it is
Creating Sub package in a package: We can create sub package in a package in the format:
package packagenamesubpackagename;
eg: package pack1pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package To use the
classes and interfaces of pack2, we can write import statement as:
import pack1pack2;
Program 5: Program to show how to create a subpackage in a package
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{
public void show ()
{
System.out.println ("Hello Java Learners");
}
}
Compiling the above program:
Access Specifier: Specifies the scope of the data members, class and methods private members of the
class are available with in the class only The scope of private members of the class is “CLASS
SCOPE” public members of the class are available anywhere The scope of public members of the class
is "GLOBAL SCOPE" default members of the class are available with in the class, outside the class
and in its sub class of same package It is not available outside the package So the scope of default
members of the class is "PACKAGE SCOPE" protected members of the class are available with in the
class, outside the class and in its sub class of same package and also available to subclasses in different
package also
Class Member Access private No Modifier protected public
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes
1. Boolean: The Boolean class wraps a value of the primitive type boolean in an object.
2. Byte: The Byte class wraps a value of primitive type byte in an object.
3. Character – Set 1, Set 2: The Character class wraps a value of the primitive type char in an object.
4. Character.Subset: Instances of this class represent particular subsets of the Unicode character set.
5. Character.UnicodeBlock: A family of character subsets representing the character blocks in the
Unicode specification.
6. Class – Set 1, Set 2 : Instances of the class Class represent classes and interfaces in a running Java
application.
7. ClassLoader: A class loader is an object that is responsible for loading classes.
8. ClassValue: Lazily associate a computed value with (potentially) every type.
9. Compiler: The Compiler class is provided to support Java-to-native-code compilers and related
services.
10. Double: The Double class wraps a value of the primitive type double in an object.
11. Enum: This is the common base class of all Java language enumeration types.
12. Float: The Float class wraps a value of primitive type float in an object.
13. InheritableThreadLocal: This class extends ThreadLocal to provide inheritance of values from
parent thread to child thread: when a child thread is created, the child receives initial values for all
inheritable thread-local variables for which the parent has values.
14. Integer :The Integer class wraps a value of the primitive type int in an object.
15. Long: The Long class wraps a value of the primitive type long in an object.
16. Math – Set 1, Set 2: The class Math contains methods for performing basic numeric operations such
as the elementary exponential, logarithm, square root, and trigonometric functions.
17. Number: The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte,
Double, Float, Integer, Long, and Short.
18. Object: Class Object is the root of the class hierarchy.
19. Package: Package objects contain version information about the implementation and specification of a
Java package.
20. Process: The ProcessBuilder.start() and Runtime.exec methods create a native process and return an
instance of a subclass of Process that can be used to control the process and obtain information about
it.
21. ProcessBuilder: This class is used to create operating system processes.
22. ProcessBuilder.Redirect: Represents a source of subprocess input or a destination of subprocess output.
23. Runtime: Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.
24. RuntimePermission: This class is for runtime permissions.
25. SecurityManager: The security manager is a class that allows applications to implement a security
policy.
26. Short: The Short class wraps a value of primitive type short in an object.
27. StackTraceElement: An element in a stack trace, as returned by Throwable.getStackTrace().
28. StrictMath- Set1, Set2: The class StrictMath contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
29. String- Set1, Set2: The String class represents character strings.
30. StringBuffer: A thread-safe, mutable sequence of characters.
31. StringBuilder: A mutable sequence of characters.
32. System: The System class contains several useful class fields and methods.
33. Thread: A thread is a thread of execution in a program.
34. ThreadGroup: A thread group represents a set of threads.
35. ThreadLocal: This class provides thread-local variables.
36. Throwable: The Throwable class is the superclass of all errors and exceptions in the Java language.
37. Void: The Void class is an uninstantiable placeholder class to hold a reference to the Class object
representing the Java keyword void.
Program 8: Write a program to print the methods in Object class and its methods count.
import java.lang.reflect.*;
class TestingClass
{
public static void main(String args[])throws Exception
{
int count=0;
Class c=Class.forName("java.lang.Object");
Method []m=c.getDeclaredMethods();
for(Method m1:m)
{
count++;
System.out.println(m1+" Method Name is "+m1.getName());
}
System.out.println("The no of Methods in this class is "+count);
}
}