Inheritance,Polymorphism,Interface

*Inheritance

-When a Student object is instantiated, the default
constructor of its superclass is invoked implicitly to do the
necessary initializations.
- After that, the statements inside the subclass's constructor
are executed.

*Superclass

-Any class above a specific class in the class hierarchy.
-A super constructor call in the constructor of a subclass will
result in the execution of relevant constructor from the
superclass, based on the arguments passed.

*Subclass

-Any class below a specific class in the class hierarchy.
A subclass can also explicitly call a constructor of its
immediate superclass.

●Benefits of Inheritance

-Benefits of Inheritance in OOP : Reusability
– Once a behavior (method) is defined in a superclass, that behavior
is automatically inherited by all subclasses.
– Thus, you can encode a method only once and they can be used by
all subclasses.
– A subclass only needs to implement the differences between itself

●Overriding Methods

- If for some reason a derived class needs to have a different
implementation of a certain method from that of the
superclass, overriding methods could prove to be very
useful.
- A subclass can override a method defined in its superclass
by providing a new implementation for that method.


●Final Methods and classes

– Methods that cannot be overridden
– To declare final methods, we write,
public final [returnType] [methodName]([parameters]){
-Static methods are automatically final.

*Polymorphism

– The ability of a reference variable to change behavior according to
what object it is holding.
– This allows multiple objects of different subclasses to be treated as
objects of a single superclass, while automatically selecting the
proper methods to apply to a particular object based on the subclass
it belongs to.
-Given the parent class Person and the subclass Student of
the previous examples, we add another subclass of Person
which is Employee.

● Abstract class
– a class that cannot be instantiated.
– often appears at the top of an object-oriented programming class
hierarchy, defining the broad types of actions possible with objects
of all subclasses of the class.
- When a class extends the LivingThing abstract class, it is
required to override the abstract method walk(), or else, that
subclass will also become an abstract class, and therefore
cannot be instantiated.
- abstract methods
– methods in the abstract classes that do not have implementation
– To create an abstract method, just write the method declaration
without the body and use the abstract keyword

*Interface

– is a special kind of block containing method signatures (and possibly
constants) only.
– defines the signatures of a set of methods, without the body.
– defines a standard and public way of specifying the behavior of
classes.
– allows classes, regardless of their locations in the class hierarchy, to
implement common behaviors.
– NOTE: interfaces exhibit polymorphism as well, since program may
call an interface method, and the proper version of that method will
be executed depending on the type of object passed to the interface
method call.
- To reveal an object's programming interface without
revealing its class
- To model multiple inheritance which allows a class to have
more than one superclass

Working with the Java Class

Object-Oriented programming or OOP

– Revolves around the concept of objects as the basic elements of
your programs.
– These objects are characterized by their properties and behaviors.

Encapsulation


– the method of hiding certain elements of the implementation of a
certain class.
– By placing a boundary around the properties and methods of our
objects, we can prevent our programs from having side effects
wherein programs have their variables changed in unexpected ways.

Class & Objects

Class
– can be thought of as a template, a prototype or a blueprint of an object
– is the fundamental structure in object-oriented programming


Two types of class members:

– Fields (properties or attributes)
● specify the data types defined by the class
– Methods.
● specify the operations


Object

– is composed of a set of data (properties) which are variables describing
the essential characteristics of the object, and consists of a set of
methods (behavior) that describes how an object behaves.
– An object is an instance of a class.

Class Variables

-● Classes consist of
– Instance variables
– Instance methods
– Class Variables (static member variables)
● variables that belong to the whole class.
● This means that they have the same value for all the objects in the same class.

Class Instantiation

● To create an object or an instance of a class, we use the
new operator.
● For example, if you want to create an instance of the class
String, we write the following code,
String str2 = new String(“Hello world!”);
or also equivalent to,
String str2 = "Hello";

The new operator
– allocates a memory for that object and returns a reference of that
memory location to you.
– When you create an object, you actually invoke the class'
constructor.
The constructor
– is a method where you place all the initializations, it has the same
name as the class.

Method

– is a separate piece of code that can be called by a main program or
any other method to perform some specific function.


The following are characteristics of methods:

– It can return one or no values
– It may accept as many parameters it needs or no parameter at all.

Parameters are also called arguments.
– After the method has finished execution, it goes back to the method
that called it.

*Method Declaration

A method's declaration provides a lot of information about the method to the compiler, to the runtime system, and to other classes and objects.Included is not only the name of the method,but also such infomation as the return type of the method,the number and type of the arguments required by the method,and which other classes and object can call the method

While this may sound like writing a novel rather than simply declaring a method, most method attributs can be declared implicity.The only required elements of a method declaration are the method names, it return type,and a pair of parentheses().This figure shows the elements of a method declaration.



*Static Methods

– methods that can be invoked without instantiating a class (means
without invoking the new keyword).
– Static methods belong to the class as a whole and not to a certain
instance (or object) of a class.
– Static methods are distinguished from instance methods in a class
definition by the keyword static.


Parameter Passing

*Pass-by-Value

– when a pass-by-value occurs, the method makes a copy of the value
of the variable passed to the method. The method cannot
accidentally modify the original argument even if it modifies the
parameters during calculations.
– all primitive data types when passed to a method are pass-by-value.

*Pass-by-Reference

– When a pass-by-reference occurs, the reference to an object is
passed to the calling method. This means that, the method makes a
copy of the reference of the variable passed to the method.
– However, unlike in pass-by-value, the method can modify the actual
object that the reference is pointing to, since, although different
references are used in the methods, the location of the data they are
pointing to is the same.

IT-231 Java Programing

2.Introduction to Java Programming
A.History
Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is general-purpose, concurrent, class-based, and object-oriented, and is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere". Java is considered by many as one of the most influential programming languages of the 20th century, and is widely used from application software to web applications.
OAK-is the first name of Java

Genesis of java
James Gosling
Patrick Naugton
Chist Worth
Ed Frank
Mike Shireden

Two type of java program
1.Appication
2.Applet

Tokens is the smallest individual unit of programming written in array progrmming
java Tokens are devided into
1.Special Symbols
2.Word Symbols
3.Identifier

B.Java technology:

a.Programming laguage-A set of rules,symbols and special words used to construct programs

b.Development Environment
-Development Tools: The development tools provide everything you'll need for compiling, running, monitoring, debugging, and documenting your applications. As a new developer, the main tools you'll be using are the javac compiler, the java launcher, and the javadoc documentation tool.

c.Application Environment
-Application Programming Interface (API): The API provides the core functionality of the Java programming language. It offers a wide array of useful classes ready for use in your own applications. It spans everything from basic objects, to networking and security, to XML generation and database access, and more. The core API is very large; to get an overview of what it contains, consult the Java SE Development Kit 6 (JDKTM 6) documentation

d.Deployment Environment
-Deployment Technologies: The JDK software provides standard mechanisms such as the Java Web Start software and Java Plug-In software for deploying your applications to end users.

C.Java Features
a.Java Virtual Machine
Java Virtual Machines operate on Java bytecode, which is normally (but not necessarily) generated from Java source code; a JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a JVM. JVMs can also be released by other companies besides Sun (the developer of Java) — JVMs using the "Java" trademark may be developed by other companies as long as they adhere to the JVM specification published by Sun (and related contractual obligations).

The JVM is a crucial component of the Java Platform. Because JVMs are available for many hardware and software platforms, Java can be both middleware and a platform in its own right[clarification needed] — hence the trademark write once, run anywhere. The use of the same bytecode for all platforms allows Java to be described as "compile once, run anywhere", as opposed to "write once, compile anywhere", which describes cross-platform compiled languages. The JVM also enables such features as Automated Exception Handling that provides 'root-cause' debugging information for every software error (exception) independent of the source code.

The JVM is distributed along with a set of standard class libraries that implement the Java API (Application Programming Interface). An application programming interface is what a computer system, library or application provides in order to allow data exchange between them. They are bundled together as the Java Runtime Environment.


b.garbage Collection
-responsible for freeing any memory that can be freed. This happens automatically during the lifetime of the Java program.–programmer is freed from the burden of having to deallocate that memory themselves

c.Code Securety
-is attained in Java through the implementation of its Java Runtime Environment (JRE). ●JRE –runs code compiled for a JVM and performs class loading (through the class loader), code verification (through the bytecode verifier) and finally code execution
●Class Loader–responsible for loading all classes needed for the Java program–adds security by separating the namespaces for the classes of the local file system from those that are imported from network sources–After loading all the classes, the memory layout of the executable is then determined. This adds protection against unauthorized access to restricted areas of the code since the memory layout is determined during runtime
Bytecode verifier–tests the format of the code fragments and checks the code fragments for illegal code that can violate access rights to objects


D.Phases of Java Programming
a.write
-A logic error arises when the programmer has written code that compiles and executes normally, but the machine's behavior does not correspond with the original concept. An example of a logic error would be if a program intends to identify when the user clicks on a shape in the window, but the program fails to include clicks on the shape's outermost boundary.

b.compile
- Compile – during this phase, the programmer compiles the program using a command at the command line, or tools from the IDE. At this step, the Java source code is translated into bytecodes. If you are running the Java compiler from the command prompt, the command to enter is:

Command: javac HelloWorld.java*
*Below we will see common errors using the compiler.

Running the command above would compile the Java source file, HelloWorld.java, and generate a bytecode class file named, HelloWorld.class.


c.Run
-A run-time error occurs during execution; one example of a common run-time error is when the machine code instructs the computer to divide a number by zero. Often such errors crash the program; that is, execution stops abruptly.

E.Difference between Java applications and Java applets

a. Java applications
- is dependent in the sense it can perform and manipulate date without intervention from other application.The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key of java application that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature.

b.Java applets is a special type of java program that is executed via the internet
-it is tyoecal run on the web browser such as Netscape Navigator,Mozilla firefax etc.
-Applets are not allowed access to computer on which they are being run for security reason.

F.What makes Java an object oriented programming language
-Object-oriented programming is at the core of Java. In fact, all Java programs are object-
oriented—this isn't an option the way that it is in C++, for example. OOP is so integral to
Java that you must understand its basic principles before you can write even simple Java
programs. Therefore, this chapter begins with a discussion of the theoretical aspects of
OOP.

IT-231 Java Programing

1.Topics that discussed in java1
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;


A.Arrays
-An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Declaring a Variable in an Array
int[] anArray;

Initializing Array
anArray = new int[10];

B.Buffered Reader
Steps to get Input
1. Add this at the top of your code:
import java.io.*;
2. Add this statement:
BufferedReader dataIn = new BufferedReader( new
InputStreamReader( System.in) );
Declare a temporary String variable to get the input, and
invoke the readLine() method to get input from the
keyboard. You have to type it inside a try-catch block.
try{
String temp = dataIn.readLine();
}catch( IOException e ){
System.out.println(“Error in getting input”);
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
● The lines,
indicate that we want to use the classes BufferedReader,
InputStreamReader and IOException which are inside the
java.io package.
● These statements can also be written as,
import java.io.*;
BufferedReader dataIn = new BufferedReader(new InputStreamReader
( System.in) );

String name = "";
declares a String variable with identifier name.
C.JOptionPane
-JOptionPane Contains classes used for a graphical user interface (GUI) Facilitates data entry and data output. class JOptionPane contains methods that display a dialog box. The JOptionPane class provides static methods to display each type of dialog box.To get input from the use we use the code variable=JOptionPane.showInputDialog("Enter the first number");and to display the output we use the code JOptionPane.showMessageDialog(null,variable).

Class JOptionPane
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JOptionPane


D.Control Statements

if
The ifstatement is Java's conditional branch statement. It can be used to route programexecution through two different paths. Here is the general form of the if statement:


if (condition) statement1;
else statement2;

The if works like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed. In no case will both statements be executed. For
example, consider the following:
int a, b;
// ...
if(a < b) a = 0;
else b = 0;

Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else

statement always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else. Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c;
// associated with this else
}
else a = d;
// this else refers to if(i == 10)

The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-
else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;

switch
The switch statement is Java's multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression.
As such, it often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

while
The while loop is Java's most fundamental looping statement. It repeats a statement or
block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}

do-while
As you just saw, if the conditional expression controlling a while loop is initially false,
then the body of the loop will not be executed at all. However, sometimes it is desirable to
execute the body of a while loop at least once, even if the conditional expression is false
to begin with. In other words, there are times when you would like to test the termination
expression at the end of the loop rather than at the beginning. Fortunately, Java supplies
a loop that does just that: the do-while. The do-while loop always executes its body at
least once, because its conditional expression is at the bottom of the loop. Its general
form is
do {
// body of loop
} while (condition);

for
The for loop operates as follows. When the loop first starts, the initialization portion of the
loop is executed. Generally, this is an expression that sets the value of the loop control
variable, which acts as a counter that controls the loop.

As you will see, it is a
powerful and versatile construct. Here is the general form of the for statement:
If only one statement is being repeated, there is no need for the curly braces.