Interfaces as types

Interfaces as types:

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable:

public Object findLargest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ((obj1).isLargerThan(obj2) > 0)

return object1;

else

return object2;

}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.

If you make a point of implementing Relatable in a wide variety of classes, the objects instantiated from any of those classes can be compared with the findLargest()method—provided that both objects are of the same class. Similarly, they can all be compared with the following methods:

public Object findSmallest(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ((obj1).isLargerThan(obj2) < 0)

return object1;

else

return object2;

}

 

public boolean isEqual(Object object1, Object object2) {

Relatable obj1 = (Relatable)object1;

Relatable obj2 = (Relatable)object2;

if ( (obj1).isLargerThan(obj2) == 0)

return true;

else

return false;

}

These methods work for any “relatable” objects, no matter what their class inheritance is. When they implement Relatable, they can be of both their own class (or superclass) type and a Relatable type. This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.

 

Interface

Interface:

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Defining an interface is similar to creating a new class:

public interface OperateCar {

 

// constant declarations, if any

 

// method signatures

 

// An enum with values RIGHT, LEFT

int turn(Direction direction,

double radius,

double startSpeed,

double endSpeed);

int changeLanes(Direction direction,

double startSpeed,

double endSpeed);

int signalTurn(Direction direction,

boolean signalOn);

int getRadarFront(double distanceToCar,

double speedOfCar);

int getRadarRear(double distanceToCar,

double speedOfCar);

……

// more method signatures

}

Note that the method signatures have no braces and are terminated with a semicolon.

Example:
interface SessionIDCreator extends SerializableCloneable{
String TYPE = “AUTOMATIC”;
int createSessionId();
}

class SerialSessionIDCreator implements SessionIDCreator{

private int lastSessionId;
@Override
public int createSessionId() {
return lastSessionId++;
}

}

 

In above example of interface in Java, SessionIDCreator is an interface while SerialSessionIDCreator is a implementation ointerface.

 

Multiple inheritance of interfaces:

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Simple Program On Java for the implementation of Multiple inheritance using interfaces to calculate the area of a rectangle and triangle
/* Area Of Rectangle and Triangle using Interface * /
interface Area
{
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println(“Area Of Rectangle = “+ area.compute(1,2));
area = tri;
System.out.println(“Area Of Triangle = “+ area.compute(10,2));
}
}
/** OUTPUT **
Area Of Rectangle = 2.0
Area Of Triangle = 10.0

/

Abstract Methods

Abstract Methods:

An abstract class can have abstract methods. You declare a method abstract by adding the abstract keyword in front of the method declaration. Here is how that looks:

public abstract class MyAbstractClass {

 

public abstract void abstractMethod();

}

An abstract method has no implementation. It just has a method signature.

If a class has an abstract method, the whole class must be declared abstract. Not all methods have to be abstract, even if the class is abstract. An abstract class can have a mixture of abstract and non-abstract classes.

Subclasses of an abstract class must implement (override) all abstract methods of its abstract superclass. The non-abstract methods of the superclass are just inherited as they are. They can also be overridden, if needed.

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

 

public void abstractMethod() {

System.out.println(“My method implementation”);

}

}

Notice how MySubClass has to implement the abstract method abstractMethod() from its superclass MyAbstractClass.

The only time a subclass of an abstract class is not forced to implement all abstract methods of its superclass, is if the subclass is also an abstract class.

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Support we have four java class A, B, C, D

We start with simple example

1. Java Simple Inheritance Example

Class A

public class A {

 

public void a(){

System.out.println(“class A”);

}

}

Class B

public class B extends A{

 

public void a(){

System.out.println(“class B”);

}

}

Class C

public class C extends B{

 

public void a(){

System.out.println(“class C”);

}

}

Class D

public class D {

 

public static void main(String[] args) {

A a=new A();

A b=new B();

A c=new C();

 

a.a();

b.a();

c.a();

}

}

Output

class A
class B
class C

Flexibility through abstraction:

Abstraction in Java is achieved using interfaces and abstract class. abstract means something which is not complete or concrete but abstraction itself is a great programming concept and allow you to write code which is more flexible to change.

Searching elements in DOM

Most of time, to react on user-triggered event, we need to find and modify elements on the page.

The childNodeschildren and other helper links are helpful, but they allow to move between adjacent elements only.

Fortunately, there are more global ways to query DOM.

Methods

document.getElementById

A fastest way to obtain an element is to query it by id.

The following example queries the document for a div with id='info'. It doesn’t matter where is the node in the document, it will be found.

 

1 <body>
2   <div id="info">Info</div>
3   <script>
4     var div = document.getElementById('info')
5     alert( div.innerHTML )
6   </script>
7 </body>

 

Note, there can be only one element with certain id value. Of course, you can violate that and put many elements with same ids in the markup, but the behavior of getElementById in this case will be buggy and inconsistent across browsers. So it’s better to stick to standards and keep a single element with certain id.

If no element is found, null is returned.

Implicit id-valued variables

All browsers implicitly create a variable for every id.

For instance, run the following code. It will output “test”, because a is IE-generated reference to the element.

1 <div id="a">test</div>
2 <script>
3   alert(a)
4 </script>

 

 

document/node.getElementsByTagName

This method searches all elements with given tagname and returns an array-like list of them. The case doesn’t matter.

 

// get all div elements
var elements = document.getElementsByTagName('div')

 

The following example demonstrates how to obtain a list of all INPUT tags of the document and loop over results:

 

<table id=”myTable”>
<tr>
<td>Your age:</td>

<td>
<label>
<input type=”radio” name=”age” value=”young” checked/> under 18
</label>
<label>
<input type=”radio” name=”age” value=”mature”/> from 18 to 50
</label>
<label>
<input type=”radio” name=”age” value=”senior”/> older than 60
</label>
</td>
</tr>

</table>

<script>
var elements = document.getElementsByTagName(‘input’)
for(var i=0; i<elements.length; i++) {
var input = elements[i]
alert(input.value+’: ‘+input.checked)
}
</script>

It is also possible to get a first element by direct referencing:

var element = document.getElementsByTagName('input')[0]

 

There is a way to get all elements by specifying '' instead of the tag:

// get all elements in the document
document.getElementsByTagName('*')

 

Limit search by parent element

getElementsByTagName can be called on a document, but also on a DOM element.

The example below demonstrates that by calling getElementsByTagName inside another element:

<ol id=”people”>
<li>John</li>
<li>Rodger</li>
<li>Hugo</li>
</ol>
<script>

var elem = document.getElementById(‘people’)

var list = elem.getElementsByTagName(‘li’)
alert(list[0].innerHTML)

</script>

elem.getElementsByTagName(‘li’) finds all LI inside elem. The element before the dot is called *the searching context.

document.getElementsByName

For elements which support the name attribute, it is possible to query them by name.

In the example above, it was possible to use the code:

var elements = document.getElementsByName('age')

 

document/node.getElementsByClassName

This method is supported in all modern browsers excluding IE<9.

It performs a search by class name, not attribute. In particlar, it understands multiple classes.

The following example demonstrates how it finds an element using one of the classes.

Please use other browser than IE<9 to run it.

 

1 <div class="a b c">Yep</div>
2 <script>
3 alert( document.getElementsByClassName('a')[0].innerHTML )
4 </script>

 

Like getElementsByTagName, it can be called for a DOM element.

 

Practice

Consider the following html:

 

<!DOCTYPE HTML>
<html>
<body>
<label>The table</label>

<form name=”age-form”>

<table id=”age-table”>
<tr>
<td id=”age-header”>Your age:</td>
<td>
<label>
<input type=”radio” name=”age” value=”young”/> under 18
</label>
<label>
<input type=”radio” name=”age” value=”mature”/> 18 to 50
</label>
<label>
<input type=”radio” name=”age” value=”senior”/> after 60
</label>
</td>
</tr>
</table>

</form>
</body>

Here are the tasks which base on the HTML above.

Find all labels inside the table. The result should be an array (or pseudo-array) of labels.

Solution

The solution:

var table = document.getElementById('age-table')
var labels = table.getElementsByTagName('label').

Summary

There are 5 main ways of querying DOM:

  1. getElementById
  2. getElementsByTagName
  3. getElementsByName
  4. getElementsByClassName (except IE<9)

All of them can search inside any other element.

Modifying the document

DOM modifications is the key to making pages dynamic. Using the methods described below, it is possible to construct new page elements and fill them on-the-fly.

Creating elements

There are following methods for creating new elements in DOM:

document.createElement(tag)
Creates a new DOM element of type node:

var div = document.createElement('div')
document.createTextNode(text)
Creates a new DOM element of type text:

var textElem = document.createTextNode('Robin was here')

The createElement is the most commonly used method, but createTextNode is also good. It creates a text node that can be appended to another element.

For an empty element, creating a text node and appending it works much faster than innerHTML in most modern browsers.

But innerHTML is simpler and supports nested tags, so they both find their place in the world.

 

Cloning

An element can also be cloned:

elem.cloneNode(true)
Clones an element deeply, with all descendants.
elem.cloneNode(false)
Clones an element only, with attributes, but without children.

 

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p id="demo">Click the button to copy an item from one list to another</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var itm=document.getElementById("myList2").lastChild;
var cln=itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
</script>

<p>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be cloned.</p>
</body>
</html>

Adding elements

To do something with the element, you need to call the corresponding method of its parent:

parentElem.appendChild(elem)
Appends elem to the children of parentElem.The following example demonstrates creating and adding new element to BODY:

<div>…</div>
<script>
var div = document.body.children[0]

var span = document.createElement(‘span’)
span.innerHTML = ‘A new span!’
div.appendChild(span)
</script>

The new node becomes a last child of the parentElem.

 

parentElem.insertBefore(elem, nextSibling)
Inserts elem into the children of parentElem before the element nextSibling.The following example inserts a new node before the first child:

<div>

</div>
<script>
var div = document.body.children[0]

var span = document.createElement(‘span’)
span.innerHTML = ‘A new span!’
div.insertBefore(span, div.firstChild)
</script>

Note that you insertBefore with second argument null works as appendChild.

 

elem.insertBefore(newElem, null// same as
elem.appendChild(newElem)

 

All insertion methods return the inserted node.

Removing nodes

There are two main methods for removing nodes from DOM:

parentElem.removeChild(elem)
Remove the elem from the children of parentElem.
parentElem.replaceChild(elem, currentElem)
Replace the child element of parentElem, referenced by currentElem with the elem.

Both of them return a removed node which can later be reinserted into the DOM.

 

If you want to move an element, you don’t have to remove it first.

elem.appendChild/insertBefore remove elem from it’s previous place automatically.

The following example moves the last child to the top of children list:

<div>First div</div>
<div>Last div</div>
<script>
var first = document.body.children[0]
var last = document.body.children[1]

document.body.insertBefore(last, first)
</script>

The removal occurs automatically when insertion methods are called for a node which already has a parent.

 

Tasks and examples

Write a function which removes an element from DOM without referencing its parent.

The syntax should be: remove(elem)

 

<div>Very</div>
<div>Secret</div>
<div>Child</div>

<script>
var elem = document.body.children[0]

function remove(elem) { /* your code */
remove(elem) // <– should remove the element
</script>

Open solution

 

The parent of elem is referenced by the parentNode property.

And better don’t forget to return the removed element for compatibility.

So the code can be like this:

function remove(elem) {
  return elem.parentNode.removeChild(elem)
}

 

Write a function insertAfter(elem, refElem) to insert elem right after refElem.

<div>Very</div>
<div>Secret</div>

<script>
var elem = document.createElement(‘div’)
elem.innerHTML = ‘**Child**’

function insertAfter(elem, refElem) { /* your code */

insertAfter(elem, document.body.firstChild) // <— should work
insertAfter(elem, document.body.lastChild) // <— should work

</script>

Solution

To insert an element after refElem, we can insert it before refElem.nextSibling.

But what if there is no nextSibling? That means refElem is the last child of its parent, so we can just call appendChild.

The code:

function insertAfter(elem, refElem) {
var parent = refElem.parentNode
var next = refElem.nextSibling
if (next) {
return parent.insertBefore(elem, next)
} else {
return parent.appendChild(elem)
}
}

But the code could be much shorter if it used insertBefore null second argument feature:

function insertAfter(elem, refElem) {
    return elem.parentNode.insertBefore(elem, refElem.nextSibling)
}

If there is no nextSibling then the second argument of insertBefore becomes null and then insertBefore(elem,null) works as appendChild.

Write a function removeChildren to remove all children of an element.

<div>Very</div>
<div>Secret</div>
<div>Children</div>

<script>
function removeChildren(elem) { /* your code */

removeChildren(document.body) // makes BODY absolutely empty
</script>

Solution

First, let’s check a way how it shouldn’t be done

1 function removeChildren(elem) {
2   for(var k=0; k<elem.childNodes.length;k++) {
3     elem.removeChild(elem.childNodes[k])
4   }
5 }

If you check it in action – you’ll find that it doesn’t work.

That’s because childNodes always starts from 0, it autoshifts when first child is removed. But k increases +1 every iteration. So, k skips half of nodes.

The right solution:

1 function removeChildren(elem) {
2    while(elem.lastChild) {
3        elem.removeChild(elem.lastChild)
4    }
5 }

Another solution:

function removeChildren(elem) {
   elem.innerHTML = ''
}

 

 

Create an interface to generate the list.

For each item:

  1. Prompt the user for it’s contents.
  2. Create the item and append it to UL.
  3. The process ends when user presses ESC.

All elements must be created dynamically.

P.S. prompt returns null if user pressed ESC.

Solution

The solution is self-descriptive:

<!DOCTYPE HTML>

<html>
<body>
<h1>Creation of the list</h1>

<script>
var ul = document.createElement(‘ul’)
document.body.appendChild(ul)

while (true) {
var data = prompt(“Enter the contents for the item”, “”)

if (data === null) {
break
}

var li = document.createElement(‘li’)
li.appendChild(document.createTextNode(data))
ul.appendChild(li)
}
</script>

</body>
</html>

Note checking for null value as a loop-breaking condition. The prompt only returns it when ESC is pressed.

LI contents is populated by document.createTextNode to ensure proper work of <, > etc.

Summary

Creation methods:

  • document.createElement(tag) – creates a new element node.
  • document.createTextNode(value) – creates a new text node with given value
  • elem.cloneNode(deep) – clones the element

Inserting and removing methods are called from parent node. All of them return elem:

  • parent.appendChild(elem)
  • parent.insertBefore(elem, nextSibling)
  • parent.removeChild(elem)
  • parent.replaceChild(elem, currentElem)

Traversing the DOM

An access always starts from the document.

This object provides a variety of methods to search and modify elements.

The root: documentElement and body

The root is the DOM always document.documentElement. This special property will give access to the topmost HTML tag.

Another starting point can be the document.body, which represents the BODY tag.

documentElement

Both entry points are valid. But document.body can be null.

For example, you access document.body from an inline script in the HEAD, prepare to see null instead. That’s natural, because there is no BODY yet.

In the example below, first alert outputs null:

 

01 <!DOCTYPE HTML>
02 <html>
03     <head>
04         <script>
05             alert("Body from HEAD: "+document.body) // null
06         </script>
07     </head>
08     <body>
09         <div>The document</div>
10
11         <script>
12             // different browsers output different text here,
13             // because of different implementations of toString
14
15             alert("Body from inside body: " + document.body)
16         </script>
17     </body>
18 </html>

Open the code in new window

Contrary to this, document.documentElement is available always.

Also note that document.body can’t be undefinedIn the world of DOM, an “element not found” or “no such element” is always null.

 

As a more general rule than described above, it is impossible to reference elements that are not yet rendered at the time of script execution.

 

  • Write the code to access the UL using children.
  • Write the code to access the second LI using children.
Solution

The code is cross-browser:

document.body.children[1]
document.body.children[1].children[1]

It works fine, because there are no comment nodes before UL, so children indexes are same for IE<9 and other browsers.

 

Getting a list of children is not enough for convenient walking around elements.
So, there are additional properties for siblings, parent, etc.

The firstChild and the lastChild

The firstChild and lastChild properties allow to quickly access first or last child.

children

They are basically same as corresponding childNodes indexes:

1 var body = document.body
2
3 alert(body.firstChild === body.childNodes[0])
4 alert(body.lastChild === body.childNodes[body.childNodes.length-1])

 

parentNodepreviousSibling and nextSibling

  • The parentNode property references the parent node. It equals null fordocument.documentElement.
  • The previousSibling and nextSibling allow to access the left or the right neightbour.

For example:

01 <!DOCTYPE HTML>
02 <html>
03 <head>
04    <title>My page</title>
05 </head>
06 <body>
07     <div>The header</div>
08
09     <ul><li>A list</li></ul>
10
11     <div>The footer</div>
12 </body>
13
14 </body>
15 </html>

Picture for the document above (without whitespace nodes):

 

siblings

The browser always maintains correct helper links. It is possible to modify the DOM, add/remove elements, but no need to reassign the links manually, browser does that.

 

Write the code to check if the DOM Node elem is totally empty. That is, there are no children or text in it.

 

if (/*... put here your code to check if the elem is empty... */)

 

Open solution

Is it right that document.body.lastChild.nextSibling is always null?

.. Same question about document.body.children[0].previousSibling ?

Open solution

 

Summary

The DOM tree is tightly interlinked:

up
parentNode
down
children/childNodesfirstChildlastChild
left/right
previousSibling/nextSibling

Browser guarantees that the links are always correct. All of them are read-only.

If there is no such element (child, parent, neighbour etc), the value is null.

haris dic.

import java.util.ArrayList;

import java.util.Iterator;

import java.util.*;

/**

* class SpellChecker for a text application (for example, a word processor, or something similar).

*

* @author (Waqar Ahmad 116-bscs-2010,Haris zeeshan 105-bscs-2010,Ammar Hassan 60-bscs-2012,Ammar zaheer 69-bscs-2009)

* @version (1.0)

*/

public class SpellChecker

{

DictReader dr;

private ArrayList<String> dic;

private ArrayList<String> listofWords;

/**

* Constructor for objects of class SpellChecker

*/

public SpellChecker()

{

dr=new DictReader(“words.txt”);

dic=dr.getDictionary();

listofWords=new ArrayList<String>();

}

//########## Base Task Level 1 impelements by Ammar hassan and Ammar zaheer

/**

* This method returns the number of words in the dictionary.

*/

public int numberOfWords()

{

return dic.size();

}

/**

* This method returns true, if (and only if) the given word is found in the dictionary.

*/

public boolean isKnownWord(String word)

{

if(dic.contains(word))

return true;

else

return false;

}

/**

* This method returns true if (and only if) all words in the given list are found in the dictionary.

*/

public boolean allKnown(ArrayList<String> words)

{

for(int i=0;i<words.size();i++)

{

if(!isKnownWord(words.get(i).toLowerCase()))

return false;

}

return true;

}

//######### Base Task Level 2 impelements by Waqar Ahmad & Haris zeeshan

/**

* This method returns a list of all words from the dictionary that start with the given prefix.

*/

public ArrayList<String> wordsStartingWith(String prefix)

 

{

Iterator <String>it=dic.iterator();

while(it.hasNext())

{

String ch=it.next();

if(ch.startsWith(prefix.toLowerCase()) || ch.startsWith(prefix.toUpperCase()))

{

listofWords.add(ch);

}

}

return listofWords;

}

/**

* This method returns a list of all words from the dictionary that include the given substring.

*/

public ArrayList<String> wordsContaining(String text)

{

String s1;

ArrayList<String> wordsList=new ArrayList();

for(int i=0;i<dic.size();i++)

{

s1=dic.get(i);

if (s1.toLowerCase().contains(text.toLowerCase()) || s1.toUpperCase().contains(text.toUpperCase()))

{

wordsList.add(s1);

}

}

return wordsList;

}

//######### Base tasks (level 3) impelements by Waqar Ahmad

/**

* Insert the given word into the dictionary if it does not exist in it.

* The word should only be inserted if it does not already exist in the dictionary.

*/

public void insert(String newWord)

{

boolean isExist=isKnownWord(newWord);

if(isExist==false)

{

dic.add(newWord);

}

Collections.sort(dic);

}

/**

* Remove the given word from the dictionary.

* If the word was successfully removed, return true.

* If not (for example it did not exist) return false.

*/

public boolean remove(String newWord)

{

if(dic.contains(newWord))

{

int a=dic.indexOf(newWord);

dic.remove(a);

return true;

}

else

return false;

}

/**

* Method use to write ArrayList on a text File

*/

public void save()

{

dr.save(dic);

}

//#########   Challenge tasks  co-effort of group on these Methods

/**

* Return true if (and only if) the given word is a palindrome

*/

public boolean isPalindrome(String word)

{

int a=word.length()-1;

for(int i=0;i<=a/2;i++)

{

if(word.toLowerCase().charAt(i)==word.toLowerCase().charAt(a))

{    a–;

}

else

{

return false;

}

}

if(dic.contains(word))

{

System.out.println(“Dictionary not Contains Given Word !!”);

}

else

{

System.out.println(“word dose not exist in dic”);

}

return true;

}

/**

* Return a list of all words that are anagrams of the given word.

* Anagrams are treated as case-insensitive.

*/

public ArrayList<String> anagrams(String word)

{

// trying to complete ,but Cannot achive this goal

return dic  ;

}

/**

* . Return a list of words that are in one of the dictionaries, but not in the other.

*   pass another dictionary as a parameter

*/

public ArrayList<String> difference(ArrayList<String> dictionary)

{

ArrayList <String> difWords=new <String> ArrayList();

for(int index=0;index<=dictionary.size();index++)

{   String word=dictionary.get(index);

if(!dic.contains(word))

{

difWords.add(word);

}

}

return difWords;

}

}

Spell Checker

import java.util.*;

/**

* Its a class which takes Dictionary from the class DictReader and Checks

* different methods upon it.

*

* @author (Farhan ullah(033-BSCS-2010), Zaeem Nazir(117-BSCS-2010), Mir Qasim(111-BSCS-2010),

*          Ahmad Butt(066-BSCS-2010) )

* @version (SpellCheck ver.1.0)

*/

 

public class SpellChecker

{

private ArrayList<String> words;

private ArrayList<String> anagrams= new ArrayList<String>();

private DictReader readers;

/**

* Constructor for objects of class SpellChecker The Constructor of the

* Class Spell Checker loads the whole dictionary in the text file to the

* memory and save it to the arraylist words

*/

public  SpellChecker()

{

// words= new ArrayList<String>();

readers=new DictReader(“words.txt”);

words=readers.getDictionary();

}

// ———-LEVEL 1———-

/**

* The Method is Implemented by Ahmad Butt. The Function runs an iterator

* and shows the size of the arraylist The Words in the dictionary are

* seprated by Space so each line is an index and no of index equal to the

* total number of word.

*

*/

 

public int numberOfWords()

{

int size;

size=words.size();

return size;

 

}

 

/**

* The Method is Implemented by Ahmad Butt.The case insensitive method is

* made by Zaeem Nazir. The method isKnownWord takes an input from the user

* and it checks it weather the word is in the included dictionary or not.

* The Word is first changed to the lowercase and the enhanced for loop is

* used over the whole arraylist and the word is searched

*/

public boolean isKnownWord(String word)

{

boolean number=false;

if(words.contains(word))

{

number=true;

}

return number;

}

/**

* This method is a bit same to the previous one. This is also implemeted by Ahamd

* Butt. This method takes an arraylist and compare it to existing array

* list words

*/

public boolean allKnown(ArrayList<String>  inputList)

{

 

for(String group: inputList)

{

boolean allWords=false;

for(String list: words)

{

if(group.equals(list))

{

allWords=true;

}}

 

if(allWords!=true)

{

return false;

}

}

return true;

}

// ————— level 2 —————-

/**

* This method is implemented by Zaeem Nazir. This method takes a prefix in

* format string from user and then compare it to the whole dictionary and

* all the words which start with the given prefix are shown This method is

* case insensitive. The word “Glib” and “glib” are same.

*/

 

public ArrayList<String> wordsStartingWith(String prefix)

{

ArrayList<String> availableList=new ArrayList<String>();//making of a arry list

String caseChanger=prefix.toUpperCase();

String caseChanger2;

for(String storeList: words)//variable name storelist type string…save words index

{

caseChanger2=storeList.toUpperCase();

if(caseChanger2.startsWith(caseChanger))//function starwith

{

availableList.add(storeList);

}

 

}

return availableList;

 

}

/**

* This method is implemented by Zaeem Nazir. This method takes a word in

* format string from user and then compare it to the whole dictionary and

* all the words which start with the given text are shown This method is

* case insensitive. The word “play” and “Play” are same.

*/

public ArrayList<String> wordsContaining(String text)

{

ArrayList<String> newList= new ArrayList<String> ();

String converter= text.toUpperCase();

String converter2;

for(String checker: words)

{

converter2=checker.toUpperCase();

if(converter2.contains(converter))

{

newList.add(checker);

}

}

return newList;

}

 

// ————— level 3 —————-

/**

* This method is implemented by Mir Qasim. This is a simple method

* which takes a input and checks weather the given word is already in

* dictionary or not if word is not present then it is added to the

* arraylist

*/

public boolean insert(String newWord)

{

boolean checker=false;

if(words.contains(newWord))

{

return checker=false;

}

else

{

words.add(newWord);

checker=true;

Collections.sort(words);

}

return checker;

} /**

* This method is implemented by Mir Qasim. This is a simple method

* which checks a word is present in dictionary or not if it is present then

* it removes it from the dictionary

*

*/

public boolean remove(String newWord)

{

boolean remover=false;

remover=isKnownWord(newWord);

if(remover=true)

{

words.remove(newWord);

}

return remover;

}

/**

* This method is implemented by Mir Qasim. This method simply saves

* the arraylist file to the disk in text format.

*/

public void save()

{

DictReader dictreader=new DictReader(“words.txt”);//class name..object name…new costruter

dictreader.save(words);

}

// ———————- Challenge Tasks—————

/**

* This method is implemented by Farhan Ullah using the existing

* function isKnown by Ahmad Butt and the Caseinsensitive logic by Zaeem

* Nazir. This method gets an input from the user and then reverses it then

* it compares it to the dictionary if the word is found then it is a

* Palindrome.

*/

public boolean isPalindrome(String word) {

boolean result = false;

String revWord = word;

StringBuffer reader = new StringBuffer(revWord);

revWord = reader.reverse().toString();

result = isKnownWord(revWord); // isKnownWord Already Made Function

// above.

return result;

 

}

/**

* This method is implemented by Farhan Ullah. This mehod takes a word in perimeter and returns a list of words that are anagrams of that word.

*/

public ArrayList<String> anagrams(String word) {

word=word.toLowerCase();

ArrayList<String> anag=new ArrayList<String>();

int size=word.length();

Iterator it=words.iterator();

while(it.hasNext())

{

int flag=0;

String check=(String)it.next();

 

if(check.length()==size)

{

char x[] = new char[size];

x=(check.toLowerCase()).toCharArray();

if(!check.equals(word))

{

for(int i=0;i<size;i++)

{

for(int j=0;j<size;j++)

{

if(word.charAt(i)==x[j])

{

x[j]=’0′;

flag++;

break;

}

}

}

}

}

if(flag==size)

anag.add(check);

 

}

return anag;

}

 

/**

* This method is implemented by Farhan Ullah. This can be called a

* blueprint of the exisiting method it takes two dictionaries and comapre

* them to each other and check the word which are in only one dictionary

* and prints them.

*/

public ArrayList<String> difference(ArrayList<String> dictionary) {

ArrayList<String> difference = new ArrayList<String>();

for (String input : dictionary) {

boolean result = false;

for (String word : words) {

if (input.equals(word)) {

result = true;

}

}

if (result != true) {

difference.add(input);

}

}

return difference;

}

 

 

}

 

 

 

 

 

 

 

 

 

POLYMORPHISM IN JAVA

Polymorphism:

The word Polymorphism means of many forms.In programming this word is meant to reuse the single code multiple times. In object oriented programming its a big question that why the Polymorphism is done, what is the purpose of it in our code?

There are lots of people who don’t even know the purpose and usage of Polymorphism.Polymorphism is the 3rd main pillar of OOP without it the object oriented programming is incomplete. Lets go in the depth of Polymorphism.

Why Polymorphism is done in OOP?

Its obvious that when we do inheritance between two classes, all the methods and properties of the first class are derived to the other class so that this becomes the child class which  adobes all the functionality of base class.It can also possesses its own separate methods.

But there is a big problem in inheriting the second class to the first class as it adobes all the methods same as the base class has,which  means that after inheritance both(base class& child class) have the methods of same name and same body as shown in this example:~
Base class:
public class fish
{
  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
  }
Derieved Class:
class Dolphen:fish
{

  public void eat()
   {
        console.writeline("fish eat");
    }
  public void swim()
   {
          console.writeline("fish swim");
    }
}
In this example it is clear that when we Inherit two classes, all the methods with the same name and same body are adobed by the derived class as shown above.Both methods have the same name but if we change the body of the second method then it makes Compiler disturb whether to compile base class method or derived classes.
To remove this problem and to tell the compiler that which method is to be executed we need to use Polymorphism.

How the Polymorphism is done?

Polymorphism is used to remove the problem which is shown in the above code.It is done not by changing the name of the methods of both base & derived class.Infect it is done by adding the “virtual” keyword before the base class method, and the “override” keyword before the derived class method.As shown in this exmple:
Base Class:
public class fish
        {
            public virtual void eat()
            {
                Console.WriteLine("fish eat");
            }
            public virtual void swim()
            {
                Console.WriteLine("fish swim");
            }
        } 
 Derived Class:

class Dolphin : fish
        {

            public override void eat()
            {
                Console.WriteLine("Dolphin can eat");
            }
            public override void swim()
            {
                Console.WriteLine("Dolphin can swim");
            }
        }
This is actually the Polymorphism in which we write virtual keyword with the base class method and we write override keyword with the derived class method as we did. It helps the compiler to select the method to be executed.
Here is the complete code in which Polymorphism has been applied.
class Program
    {
        public class fish
        {
            public virtual void eat()
            {  }
            public virtual void swim()
            { }
            public virtual void dive()
            {}

        }
       public class Dolphin : fish
         {
            public override void eat()
            { Console.WriteLine("Dolphin eats Plants"); }
            public override  void swim()
            { Console.WriteLine("Dolphin swims quickly"); }
            public override  void dive()
            { Console.WriteLine("Dolphin dive deeply "); }
           public void dance()
            { Console.WriteLine("Dolphin can Dance"); }

        }
        public class Shark : fish
        {
            public override  void eat()
            { Console.WriteLine("Shark eats dead animal"); }
            public override  void swim()
            { Console.WriteLine("Sharks swim fastest than Dolphin"); }
            public override  void dive()
            { Console.WriteLine("Sharks Dive deeper than Dolphin"); }

            public void kill()
            { Console.WriteLine("Shark kills Others"); }

        }

        static void Main(string[] args)
        {
            Dolphin D = new Dolphin();
            D.dance();
            D.dive();
            D.eat();
            D.swim();
            Shark S = new Shark();
            S.kill();
            S.dive();
            S.eat();
            S.swim();
            Console.ReadLine();
        }
    }
Types of Polymorphism:
In general there are three types of polymorphism:
Overloading polymorphism:

Overloading polymorphism is where functions of the same name exist, with similar functionality, in classes which are completely independent of each other (these do not have to be children of the object class). For example, the complex class, the image class and the link class may each have the function “display”. This means that we do not need to worry about what type of object we are dealing with if all we want to do is display it on the screen.

Parametric polymorphism:

Parametric polymorphism is the ability to define several functions using the same name, but using different parameters (name and/or type). Parametric polymorphism automatically selects the correct method to be adopted according to the type of data passed in the parameter.

We can therefore define several addition() methods using the same name which calculates a sum of values.

  • The int addition(int,int) method would return the sum of two integers.
  • The float addition(float, float) would return the sum of two floats.
  • The char addition(char, char) would result as the sum of two characters as defined by the author.
  • etc.

signature is the name and type (static) given to the arguments of a function. Therefore it is a method’s signature which determines what is called on.

Inclusion polymorphism:

The ability to redefine a method in classes that are inherited from a base class is called specialization. One can therefore call on an object’s method without having to know its intrinsic type: this is inclusion polymorphism. This makes it possible to disregard the specialized class details of an object family, by masking them with a common interface (this being the basic class).

Imagine a game of chess, with the objects kingqueenbishopknightrook and pawn, each inheriting thepiece object.
The movement method could, using inclusion polymorphism, make the corresponding move according to the object class that is called on. This therefore allows the program to perform piece.movement without having to be concerned with each piece’s class.

INHERITANCE IN JAVA

Inheritance:

Inheritance is specific to object-oriented programming, where a new class is created from an existing class. Inheritance (often referred to as subclasses) comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. The main advantage of inheritance is the ability to define new attributes and new methods for the subclass which are then applied to the inherited attributes and methods. This can be used to create a highly specialized hierarchical class structure. The biggest advantage is that there is no need to start from scratch when wanting to specialize an existing class.

In inheritance where objects are defined by classes can inherit attributes and behavior from pre-existing classes called baseclasses, superclasses, or parent classes. The resulting classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance give rise to a hierarchy.

Subclasses and super classes:

subclass or child class is a derivative class that inherits one or more languages entities from one or more other classes (called superclassesbase classes, or parent classes). The semantics of class inheritance vary from language to language, but commonly the subclass automatically inherits the instance variable and member functions of its superclasses. Some languages support the inhertance of other construct as well.

Class hierarchy:

The parent-child relationship between classes can be represented in a hierarchical view often called class tree view. The class tree view starts with a general class called superclass. Derived classes (child class or subclass) become more specialized further down the tree.

Multiple inheritance:

Some object oriented languages, such as C++ allow multiple inheritance, meaning that one class can inherit attributes from two superclasses. This method can be used to group attributes and methods from several classes into one single class.

 

Inheritance and controlling access:

You control access to variables, classes, functions, and methods using access control attributes.

Table1. Access control attributes

Access control attribute keyword Access
public available to any caller
private available only to the class that defines it
protected available only to the class that defines it and to any subclasses of that class
internal available to any caller within the same package

Methods that cannot be overridden:

Just as classes may be sealed/finalized method declarations may contain method modifiers that prevent the method from being overridden (i.e. replaced with a new function with the same name and type signature in a subclass). A private method is unoverridable simply because it is not accessible by classes other than the class it is a member function of.

Overriding:

Many object-oriented programming languages permit a class or object to replace the implementation of an aspect—typically a behavior—that it has inherited. This process is usually called overriding.

Overriding introduces a complication that which version of the behavior does an instance of the inherited class use—the one that is part of its own class, or the one from the parent (base) class? The answer varies between programming languages, and some languages provide the ability to indicate that a particular behavior is not to be overridden and should behave as defined by the base class.

Inheritance vs subtyping:

Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A, and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).

class A 
{ public:
   void DoSomethingALike() const {}
};

class B : public A 
{ public:
   void DoSomethingBLike() const {}
};

void UseAnA(A const& some_A)
{
   some_A.DoSomethingALike();
}

void SomeFunc()
{
   B b;
   UseAnA(b); // b can be substituted for an A.
}

In programming languages that do not support inheritance as a subtyping mechanism, the relationship between a base class and a derived class is only a relationship between implementations (a mechanism for code reuse), as compared to a relationship between types. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail behavioral subtyping. It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected.