Download Single Inheritance example program in Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
What is a relationship?
A relationship defines the connection between objects. This explains how objects are connected to
each other’s and how they will behave.
Association
It represents a relationship between two or more objects where all objects have their own lifecycle
and there is no owner. The name of an association specifies the nature of relationship between
objects. This is represented by a solid line.
Let’s take an example of relationship between Teacher and Student. Multiple students can associate
with a single teacher and a single student can associate with multiple teachers. But there is no
ownership between the objects and both have their own lifecycle. Both can be created and deleted
independently.
Aggregation
It is a specialized form of Association where all object have their own lifecycle but there is ownership.
This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond
followed by a line.
Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to
multiple departments. Hence Teacher is a part of multiple departments. But if we delete a
Department, Teacher Object will not destroy.
Composition
It is a specialized form of Aggregation. It is a strong type of Aggregation. In this relationship child
objects does not have their lifecycle without Parent object. If a parent object is deleted, all its child
objects will also be deleted. This represents “death” relationship. This is represented by a solid
diamond followed by a line.
Let’s take an example of relationship between House and rooms. House can contain multiple rooms
there is no independent life of room and any room cannot belongs to two different house if we
delete the house room will automatically delete.
Let’s take another example of relationship between Questions and options. Single questions can
have multiple options and option cannot belong to multiple questions. If we delete questions
options will be automatically deleted.
Dependency
It represents a relationship between two or more objects where an object is dependent on another
object(s) for its specification or implementation. This is represented by a dashed arrow.
Let’s take an example of relationship between client and service. A client is dependent on the service
for implementing its functionalities.
Let’s take another example of relationship between a client and a supplier. A client is dependent on
the supplier for supplying products. If the supplier will not supply the products, client cannot use
those products.
Caught exceptions and uncaught exceptions.
Caught exceptions are called checked exceptions. Checked exception occur at compile time. Uncaught
exceptions are called unchecked exceptions. Unchecked exceptions occur at runtime. Checked
exceptions must be either declare or catch the exception. Unchecked exceptions does not need to
declare or catch the exception.
Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one
class only then we call it a single inheritance. The below flow diagram shows that
class B extends only one class which is A. Here A is a parent class of B and B would be
a child class of A.
Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits)
more than one base class. The inheritance we learnt earlier had the concept of one
base class or parent. The problem with “multiple inheritance” is that the derived
class will have to manage the dependency on two base classes.
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted
complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritance is supported in C++.
3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit
from a derived class, thereby making this derived class the base class for the new
class. As you can see in below flow diagram C is subclass or child class of B and B is a
child class of A.
Multilevel Inheritance example program in Java
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base class) of
B,C & D.
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination
of Single and Multiple inheritance. A typical flow diagram would look like below. A
hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces. yes you heard it right. By
using interfacesyou can have multiple as well as hybrid inheritance in Java.
Why Java doesn’t support multiple inheritance?
C++ , Common lisp and few other languages supports multiple inheritance while java
doesn’t support it. It is just to remove ambiguity, because multiple inheritance can
cause ambiguity in few scenarios. One of the most common scenario is Diamond
problem.
What is diamond problem?
Consider the below diagram which shows multiple inheritance as Class D extends both
Class B & C. Now lets assume we have a method in class A and class B & C overrides
that method in their own way. Wait!! here the problem comes – Because D is
extending both B & C so if D wants to use the same method which method would be
called (the overridden method of B or the overridden method of C). Ambiguity. That’s
the main reason why Java doesn’t support multiple inheritance.
How to achieve multiple inheritance in Java using
interfaces?
interface X
{
public void myMethod();
}
interface Y
{
public void myMethod();
}
class Demo implements X, Y
{
public void myMethod()
{
System.out.println(" Multiple inheritance example using interfaces");
}
}
As you can see that the class implemented two interfaces. A class can implement any number
of interfaces. In this case there is no ambiguity even though both the interfaces are having
same method. Why? Because methods in an interface are alwaysabstract by default, which
doesn’t let them to give their implementation (or method definition ) in interface itself.
Principles of OOPs
1) Encapsulation
Below is a real-life example of encapsulation.
Encapsulation is:

Binding the data with the code that manipulates it.

It keeps the data and the code safe from external interference
The whole idea behind encapsulation is to hide the implementation details from users. If a
data member is private it means it can only be accessed within the same class. No outside
class can access private data member (variable) of other class. However if we setup public
and methods to update and read the private data fields then the outside class can access
those private data fields via public methods. This way data can only be accessed by public
methods thus making the private fields and their implementation hidden for outside classes.
That’s why encapsulation is known as data hiding.
1. Objects encapsulate data and implementation details. To the outside world, an
object is a black box that exhibits a certain behavior.
2. The behavior of this object is what which is useful for the external world or other
objects.
3. An object exposes its behavior by means of public methods or functions.
4. The set of functions an object exposes to other objects or external world acts as
the interface of the object.
2) Inheritance
Below is a theoretical explanation of inheritance with real-life examples.

Inheritance is the mechanism by which an object acquires the some/all properties of
another object.

It supports the concept of hierarchical classification.
For example: Car is a classification of Four Wheeler. Here Car acquires the properties
of a four-wheeler. Other classifications could be a jeep, tempo, van etc. Four
Wheeler defines a class of vehicles that have four wheels, and specific range of
engine power, load carrying capacity etc. Car (termed as a sub-class) acquires these
properties from Four Wheeler (termed as a super-class), and has some specific
properties, which are different from other classifications of Four Wheeler, such as
luxury, comfort, shape, size, usage etc.
A car can have further classification such as an open car, small car, big car etc, which
will acquire the properties from both Four Wheeler and Car, but will still have some
specific properties. This way the level of hierarchy can be extended to any level.
Java Swing and Awt classes represent best examples for inheritance.
3) Polymorphism
Below is a real-life example of polymorphism.
Polymorphism means to process objects differently based on their data type.

In other words it means, one method with multiple implementation, for a certain class of
action. And which implementation to be used is decided at runtime depending upon the
situation (i.e., data type of the object)

This can be implemented by designing a generic interface, which provides generic
methods for a certain class of action and there can be multiple classes, which provides
the implementation of these generic methods.
Lets us look at same example of a car. A car have a gear transmission system. It has
four front gears and one backward gear. When the engine is accelerated then
depending upon which gear is engaged different amount power and movement is
delivered to the car.
Polymorphism could be static and dynamic both. Overloading is static polymorphism
while, overriding is dynamic polymorphism.

Overloading in simple words means two methods having same method name but
takes different input parameters. This called static because, which method to be
invoked will be decided at the time of compilation

Overriding means a derived class is implementing a method of its super class.
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).
What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.
What it does?
The JVM performs following operation:
5.
6.
7.
8.
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:





Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Internal Architecture of JVM
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
5) Program Counter Register:
PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:
It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the
byte code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation.Here the term ?compiler? refers to a translator from the instruction set of a
Java virtual machine (JVM) to the instruction set of a specific CPU.
Short notes : Wrapper class
Wrapper classes are used to convert any primitive type into an object.The primitive data types are not
objects, they do not belong to any class, they are defined in the language itself. While storing in data
structures which support only objects, it is required to convert the primitive type to object first, so we
go for wrapper class.
Java designers kept the two separate to keep things simple. You use the wrappers when you need
types that fit in the object oriented world - like polymorphism, collections etc. You use the primitives
when you need efficiency.
As we have already seen, a variable of primitive data type is by default passed by value and not by
reference. Quite often, there might arise the need to consider such variables of primitive data type as
reference types. The solution to this lies in the wrapper classes provided by Java. These classes are
used to wrap the data in a new object which contains the value of that variable. This object can then be
used in a way similar to how other objects are used. For example, we wrap the number 34 in an Integer
object in the following way:
Integer intObject = new Integer (34);
The Integer class is the wrapper class that has been provided for the int data type. Similarly, there are
wrapper classes for the other data types too. The following table lists the data types and their
corresponding wrapper classes.
Data Type
Wrapper Class
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
A wrapper class also contains a number of other different methods which may be used in the processing
of variables of the corresponding data type. For example, the Character wrapper class contains methods
which can be used to check if a character is a digit or a letter or a whitespace and so on.
Creating objects of the Wrapper classes
All the wrapper classes have constructors which can be used to create the corresponding Wrapper class
objects by passing either a String or a variable of the same data type as that of the type to which the
wrapper class corresponds, except for the Character wrapper class whose object cannot be created with
a String. Also, the Float wrapper class allows its object to be created using a double value.
For example, we can create an Integer object which wraps the int 34 in either of the following two ways:
Integer intObject = new Integer (34);
Integer intObject = new Integer ( "34");
Retrieving the value wrapped by a wrapper class object
Each of the eight wrapper classes have a method to retrieve the value that was wrapped in the object.
These methods have the form *Value() where star refers to the corresponding data type. For example, to
retrieve the value stored in the Integer object intObject, we use the following statement.
int x = intObject.intValue();
Similarly, we have methods for the other seven wrapper classes: byteValue(), shortValue(), longValue(),
floatValue(), doubleValue(), charValue(), booleanValue().
Auto boxing and auto unboxing
Creating a wrapper class object using the constructors and retrieving the values wrapped by those
objects using the methods as shown above can become quite cumbersome. As an alternative, there
exists auto boxing and uutounboxing. Auto boxing refers to an implicit call to the constructor and auto
unboxing refers to an implicit call to the *value() method. Therefore, a new wrapper object can be created
by specifying the value to be wrapped just as we would do for a primitive data type variable. Also, the
value can be retrieved and used in a simple way by specifying the object name. Look at the following
code:
Integer intObject = 34;
int x=intObject;
int x = intObject + 7;
The above statements are equivalent to the following set of statements
Integer intObject = new Integer (34);
int x = intObject.intValue();
int x = intObject .intValue()+ 7;
Similarly, auto boxing and auto boxing apply to other wrapper classes also.