Oops Java 1-5mod Notes (1)
Oops Java 1-5mod Notes (1)
Module 3
Syllabus
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
Inheritance: Acquiring properties from one class (Parent class) into Another class (child class)
is called Inheritance. Parent class is also called as Super class or Base class and Child class is
also called as Sub class or Derived class. Super class do not have knowledge of Sub class. But
Sub class is having knowledge of Parent Class and Its own class.
The Acquiring properties from Parent class to child class are:
Instance variables of Super class can be accessible inside subclass
Methods of super class can be accessible inside sub class.
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
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 Example: 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.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
System.out.println("barking...");}
}
class BabyDog extends Dog{
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 Example: 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.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class Cat extends Animal{
void meow(){
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
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...
Inheritance Basics: To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how, let’s begin with a short example. The following
program creates a superclass called A and a subclass called B. Notice how the keyword extends
is used to create a subclass of A.
// A simple example of inheritance.Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
Using super: 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.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
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. Sub-class variable hides the super-class variable in class sub-class.
class Animal{
String color="white";
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
}
class Dog extends Animal{
String color="black"; //this hides color in Animal
void printColor(){
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color ofAnimal class
}
}
class Mainclass{
public static void main(String[ ] args){
Dog d=new Dog();
d.printColor();
}
}
Output: black
white
class A {
int i;
private int j;
A(int a, int b) {
i=a;
j=b;
}
void addij(){
int k=i+j;
System.out.println("(i+j=)"+k);
}
}
class B extends A {
int k;
B(int a, int b, int c){
super(a,b);
k=c;
}void addik() {
System.out.println("i: " + i);
//System.out.println("j: " + j); //Error j is private cannot access j in B
System.out.println("k: " + k);
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
int c=i+k;
System.out.println("i+k="+c);
}
}
class Mainclass{
public static void main(String[ ] args){
B b=new B(1,2,3);
b.addij();
b.addik();
}
}
Output: (i+j=)3
i: 1
k: 3
i+k=4
3. super is used to invoke super-class(parent class) method.. The super keyword can
also be used to invoke the parent class method when parent class method and child class
method names are same in other words method is overridden.
Let's see a simple example:
class Animal{
void eat(){
System.out.println("All Animals can eat...");
}
}
class Dog extends Animal{
void eat(){
System.out.println("eating bread...");
}
void bark(){
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class Mainclass{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
Creating a Multilevel Hierarchy: The level of the inheritance is two or more then we can call
it as multilevel inheritance. you can build hierarchies that contain as many layers of inheritance
as you like. As mentioned, it is perfectly acceptable to use a subclass as a superclass of another.
For example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass
of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its
superclasses. In this case, C inherits all aspects of B and A. To see how a multilevel hierarchy can
be useful, consider the following program. In it, the subclass BoxWeight is used as a superclass
to create the subclass called Shipment. Shipment inherits all of the traits of BoxWeight and Box,
and adds a field called cost, which holds the cost of shipping such a parcel.
class Box {
private double width;
private double height;
private double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
}
class Shipment extends BoxWeight {
double cost;
Shipment(double w, double h, double d,double m, double c) {
super(w, h, d, m);
cost = c;
}
}
class Mainclass{
public static void main(String args[]){
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
}
}
When Constructors Are Called: When a class hierarchy is created, in what order are the
constructors for the classes that make up the hierarchy called? For example, given a subclass called B and
a superclass called A, is A’s constructor called before B’s, or vice versa? The answer is that in a class
hierarchy, constructors are called in order of derivation, from superclass to subclass. Further, since super(
) must be the first statement executed in a subclass’ constructor, this order is the same whether or not super(
) is used. If super( ) is not used, then the default or parameterless constructor of each superclass will be
executed. The following program illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
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 subclass provides
the specific implementation of the method that has been provided by one of its parent class,
it is known as method overriding.
class Bank{
int getRateOfInterest(){
return 0;
}
}
class SBI extends Bank{
int getRateOfInterest(){
return 8;
}
}
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
Dynamic Method Dispatch: Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is
important because this is how Java implements run-time polymorphism.
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r;
r = a; // r refers to an A object
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
final variable: There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can never be
changed.
class Bike9{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
} Output: Compile Time Error
Java final method: If you make any method as final, you cannot override it.
class Bike{
final void run(){
System.out.println("running");
}
}
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
class MainClass{
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
} Output: Compile Time Error
Java final class: If you make any class as final, you cannot inherit it.
final class Bike{
int add(){
return 10;
}
}
class Honda1 extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
class MainClass{
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
Abstract Classes: There are situations in which you will want to define a super-class 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 super-class 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.To declare an
abstract method, use this general form:
abstract type name(parameter-list);
As you can see,
no method body is present.
Any class that contains one or more abstract methods must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. Such objects would be useless, because an abstract
class is not fully defined.
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
An interface is defined much like a class. This is the general form of an interface:
access interface name {
type final-varname1 = value;
type final-varname2 = value;
type final-varnameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
// ...
return-type method-nameN(parameter-list);
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
interface printable{
int x=100;
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();
// obj.x++; cannot change the value of the x because it is final
}
}
Example:
interface Printable{
void print();
}
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
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();
}
}
Default Interface Methods: The non-abstract methods which are defined inside the interface are
called as Default Interface methods. The concept of default method is used to define a method with
default implementation. You can override default method also to provide more specific
implementation for the method.
interface Sayable{
default void say(){
System.out.println("Hello, this is default method");
}
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
}
}
Output:
Hello, this is default method
Work is worship
Static Methods inside Interface: You can also define static methods inside the interface. Static
methods are used to define utility methods. Static methods are nowhere related to objects. We can
access static methods using Interface name. The following example explain, how to implement
static method in interface?
interface Sayable{
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public static void main(String[] args) {
Sayable.sayLouder("Helloooo..."); // calling static method
}
}
Output: Helloooo...
Private Interface Methods: we can create private methods inside an interface. Interface allows
us to declare private methods that help to share common code between non-abstract methods.
interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
s.say();
}
}
Output: Hello... I'm private method
Object class: The Object class is the parent class of all the classes in java by default. 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. 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.
1 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.
2 public int hashCode() returns the hashcode number for this object.
3 public boolean equals(Object obj) compares the given object to this object.
public final void wait()throws causes the current thread to wait, until another
8 InterruptedException thread notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int auses the current thread to wait for the
9 nanos)throws InterruptedException specified milliseconds and nanoseconds, until
another thread notifies (invokes notify() or
notifyAll() method).
protected Object clone() throws creates and returns the exact copy (clone) of
10 CloneNotSupportedException this object.
vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)
vtucode.in
Module 4
website: vtucode.in
Defining a Package
A set of classes and interfaces grouped together are known as
Packages in JAVA.
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
While the default package is fine for short, sample programs, it is
inadequate for real applications.
This is the general form of the package statement:
Packages and Member Access
Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods.
Packages act as containers for classes and other subordinate packages.
Classes act as containers for data and code.
The class is Java’s smallest unit of abstraction. Because of the
interplay between classes and packages, Java addresses four categories
of visibility for class members:
Importing Packages.
Java includes the import statement to bring certain classes, or entire
packages, into visibility.
Once imported, a class can be referred to directly, using only its name.
The import statement is a convenience to the programmer and is not
technically needed to write a complete Java program.
If you are going to refer to a few dozen classes in your application,
however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the
package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
Here, pkg1 is the name of a top-level package, and pkg2 is the name
of a subordinate package inside the outer package separated by a dot
(.).
you specify either an explicit classname or a star (*), which indicates
that the Java compiler should import the entire package.
This code fragment shows both forms in use:
MODULE-4
CHAPTER-2
Exceptions
An exception is an abnormal condition that arises in a code sequence at run
time. In other words, an exception is a run time error
Exception-Handling Fundamentals
Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
Program statements that you want to monitor for exceptions are
contained within a try block.
If an exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and handle it in some
rational manner.
System-generated exceptions are automatically thrown by the Java
run time system.
To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by
a throws clause.
Any code that absolutely must be executed after a try block completes is
put in a finally block.
Exception Types
Exception Types
All exception types are subclasses of the built-in class Throwable.
Thus, Throwable is at the top of the exception class hierarchy.
Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches.
One branch is headed by Exception.
This class is used for exceptional conditions that user programs
should catch. This is also the class that you will subclass to create
your own custom exception types.
There is an important subclass of Exception, called
RuntimeException.
Exceptions of this type are automatically defined for the programs
that you write and include things such as division by zero and invalid
array indexing.
The other branch is topped by Error, which defines exceptions that
are not expected to be caught under normal circumstances by your
program.
Exceptions of type Error are used by the Java run-time system to
indicate errors having to do with the run-time environment, itself.
Stack overflow is an example of such an error.
we haven’t supplied any exception handlers of our own, so the
exception is caught by the default handler provided by the Java run-
time system.
Any exception that is not caught by your program will ultimately be
processed by the default handler.
The default handler displays a string describing the exception, prints
a stack trace from the point at which the exception occurred, and
terminates the program.
throw
So far, you have only been catching exceptions that are thrown by the
Java run-time system.
However, it is possible for your program to throw an exception
explicitly, using the throw statement.
The general form of throw is shown here: throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
Primitive types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions.
There are two ways you can obtain a Throwable object: using a
parameter in a catch clause or creating one with the new operator.
The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of exception.
If it does find a match, control is transferred to that statement. If
not, then the next enclosing try statement is inspected, and so on. If
no matching catch is found, then the default exception handler halts
the program and prints the stack trace.
Here is a sample program that creates and throws an exception. The
handler that catches the exception rethrows it to the outer handler.
Throws
If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception.
You do this by including a throws clause in the method’s declaration.
A throws clause lists the types of exceptions that a method might
throw. This is necessary for all exceptions, except those of type Error
or RuntimeException, or any of their subclasses.
All other exceptions that a method can throw must be declared in the
throws clause. If they are not, a compile-time error will result.
finally
finally creates a block of code that will be executed after a try /catch
block has completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no
catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch
block, via an uncaught exception or an explicit return statement, the
finally clause is also executed just before the method returns.
This can be useful for closing file handles and freeing up any other
resources that might have been allocated at the beginning of a method
with the intent of disposing of them before returning.
The finally clause is optional.
However, each try statement requires at least one catch or a finally clause
In the first form, causeExc is the exception that causes the current
exception.
That is, causeExc is the underlying reason that an exception occurred.
The second form allows you to specify a description at the same time
that you specify a cause exception.
These two constructors have also been added to the Error, Exception,
and RuntimeException classes.
The chained exception methods supported by Throwable are
getCause( ) and initCause( ).
These methods are shown in Table 10-3 and are repeated here for the
sake of discussion.
The getCause( ) method returns the exception that underlies the current
exception.
If there is no underlying exception, null is returned.
The initCause( ) method associates causeExc with the invoking
exception and returns a reference to the exception.
Thus, you can associate a cause with an exception after the exception has
been created.
However, the cause exception can be set only once.
Thus, you can call initCause( ) only once for each exception object.
Furthermore, if the cause exception was set by a constructor, then you
can’t set it again using initCause( ).
In general, initCause( ) is used to set a cause for legacy exception
classes that don’t support the two additional constructors described
earlier.
Here is an example that illustrates the mechanics of handling chained
exceptions:
MODULE-5
Chapter - 1
Multithreaded
Programming