Showing posts with label INHERITANCE. Show all posts
Showing posts with label INHERITANCE. Show all posts

Sunday, 23 September 2012

Final Keyword

/* All members and variables can be overriden by default in subclasses. Final Keyword Is Used in Java to prevent the subclass from overridding the members of the superclass. Making a method final ensures that the functionality defiened in the mathod will never be altered in any way. Similarily the value of the final variable can never be altered in any way. */
class fe
{
double fp;
int fr;

fe(double p1,int r1)
{
fp=p1;
fr=r1;
}
}

class se extends fe
{
double sp;
int sr;

se(double p1,int r1,double p2,int r2)
{
super(p1,r1);
sp=p2;
sr=r2;
}
}

final class te extends se
{
double tp;
int tr;

te(double p1,int r1,double p2,int r2,double p3,int r3)
{
super(p1,r1,p2,r2);
tp=p3;
tr=r3;
}

double average()
{
return (fp+sp+tp)/3;
}
}

class Student
{
public static void main(String args[])
{
te student = new te(75.6,40,78.6,44,70.5,48);
System.out.println("Year\tRoll no.\tPercentage");
System.out.println("FE\t"+student.fr+"\t\t"+student.fp);
System.out.println("SE\t"+student.sr+"\t\t"+student.sp);
System.out.println("TE\t"+student.tr+"\t\t"+student.tp);
System.out.println("Average performance is " + student.average());
}
}
/* Output *

Year Roll no. Percentage
FE 40 75.6
SE 44 78.6
TE 48 70.5
Average performance is 74.89999999999999 */

Student Details - Hierarchical Inheritance

--BY Joel Mathias
/* Program to Implement Hierarchical Inheritance in java Programming Language */
class Info
{
int pid;
char branch;
char year;

Info(int p,char ch,char y)
{
pid = p;
branch = ch;
year = y;
}

void display()
{
System.out.println("\nPID\t: "+pid);

System.out.print("Branch\t: ");
if(branch == 'i')
System.out.println("Information Technology");
if(branch =='e')
System.out.println("Electronics and Telecommunication");
if(branch =='c')
System.out.println("Computer Science");

System.out.print("Year\t: ");
if(year == 'f')
System.out.println("FE");
if(year == 's')
System.out.println("SE");
if(year == 't')
System.out.println("TE");
}
}

class Fe extends Info
{
int c;
int cpp;

Fe(int p,char ch,char y,int m1,int m2)
{
super(p,ch,y);
c = m1;
cpp = m2;
}

void fdisplay()
{
display();
System.out.println("Performance:");
System.out.println("\tC\t"+c);
System.out.println("\tC++\t"+cpp);
}
}

class Se extends Info
{
int vb;
int html;

Se(int p,char ch,char y,int m1,int m2)
{
super(p,ch,y);
vb = m1;
html= m2;
}

void sdisplay()
{
display();
System.out.println("Performance:");
System.out.println("\tVB\t"+vb);
System.out.println("\tHTML\t"+html);
}
}

class Te extends Info
{
int matlab;
int java;

Te(int p,char ch,char y,int m1,int m2)
{
super(p,ch,y);
matlab = m1;
java = m2;
}
void tdisplay()
{
display();
System.out.println("Performance:");
System.out.println("\tMATLAB\t"+matlab);
System.out.println("\tSJava\t"+java);
}
}

class Language
{
public static void main(String args[])
{
Fe F = new Fe(1074,'i','f',9,8);
Se S = new Se(1064,'e','s',6,8);
Te T = new Te(1054,'c','t',9,9);
F.fdisplay();
S.sdisplay();
T.tdisplay();
}
}

/* Output *


PID : 1074
Branch : Information Technology
Year : FE
Performance:
C 9
C++ 8

PID : 1064
Branch : Electronics and Telecommunication
Year : SE
Performance:
VB 6
HTML 8

PID : 1054
Branch : Computer Science
Year : TE
Performance:
MATLAB 9
SJava 9 */

Percentage Of Student - Multiple Inheritance

--BY Joel Mathias
Program that makes use of Multilevel Inheritance in java
/* program To Implement Multilevel Inheritance */
class Fe
{
double fp;
int fr;

Fe(double p1,int r1)
{
fp = p1;
fr = r1;
}
}

class Se extends Fe
{
double sp;
int sr;

Se(double p1,int r1,double p2,int r2)
{
super(p1,r1);
sp = p2;
sr = r2;
}
}

class Te extends Se
{
double tp;
int tr;

Te(double p1,int r1,double p2,int r2,double p3,int r3)
{
super(p1,r1,p2,r2);
tp = p3;
tr = r3;
}

double average()
{
return (fp+sp+tp)/3;
}
}

class Student
{
public static void main(String args[])
{
Te student = new Te(78.5,41,71.73,44,79.8,48);
System.out.println("Year\tRoll no.\tPercentage");
System.out.println("FE\t"+student.fr+"\t\t"+student.fp);
System.out.println("SE\t"+student.sr+"\t\t"+student.sp);
System.out.println("TE\t"+student.tr+"\t\t"+student.tp);
System.out.println("\nAverage Performance is " + student.average());
}
}

/* Output *

Year Roll no. Percentage
FE 41 78.5
SE 44 71.73
TE 48 79.8

Average Performance is 76.67666666666668 */

Volume Of Sphere

Single Inheritance Program To Find The Volume Of A cylinder and a sphere
/* Program To Implement Simple Program On Single Inheritance */
class Sphere
{
double r;

double area()
{
return (r * r * r * 4 * 3.1416 / 3);
}

}

class Cylinder extends Sphere
{
double h;

double area()
{
return 3.1416 * r * r * h;
}

}

class Volume
{
public static void main(String args[])
{
Cylinder C = new Cylinder();
C.r = 2.0;
C.h = 6.0;
double cyl = C.area();

Sphere S = new Sphere();
S.r = 5.0;
double sph = S.area();

System.out.println("Area of sphere is "+sph+" and area of cylinder is "+cyl);
}
}

/* OUTPUT *

Area of sphere is 523.6 and area of cylinder is 75.3984 */

Single Inheritance To Find Area Of Rectangle

Single Inheritance inherits the properties of one class into another class here is a program that implements single inheritance to find area of a rectangle..

/* Single Inhetitance To Find Area Of Rectangle */
class Dimensions
{
int length;
int breadth;
}

class Rectangle extends Dimensions
{
int a;
void area()
{
a = length * breadth;
}

}

class Area
{
public static void main(String args[])
{
Rectangle Rect = new Rectangle();
Rect.length = 7;
Rect.breadth = 16;
Rect.area();
System.out.println("The Area of rectangle of length "
+Rect.length+" and breadth "+Rect.breadth+" is "+Rect.a);
}
}

/* Output *

The Area of rectangle of length 7 and breadth 16 is 112 */

Multiple Inheritance using Interfaces

What Is an Interface? In general, an interface is a device or a system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people, and the protocol of behavior enforced in the military is the interface between people of different ranks.

Within the Java programming language, an interface is a type, just as a class is a type. Like a class, an interface defines methods. Unlike a class, an interface never implements methods; instead, classes that implement the interface implement the methods defined by the interface. A class can implement multiple interfaces.

The bicycle class and its class hierarchy define what a bicycle can and cannot do in terms of its "bicycleness." But bicycles interact with the world on other terms. For example, a bicycle in a store could be managed by an inventory program. An inventory program doesn’t care what class of items it manages, as long as each item provides certain information, such as price and tracking number. Instead of forcing class relationships on otherwise unrelated items, the inventory program sets up a protocol of communication. This protocol comes in the form of a set of method definitions contained within an interface. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on.

To work in the inventory program, the bicycle class must agree to this protocol by implementing the interface. When a class implements an interface, the class agrees to implement all the methods defined in the interface. Thus, the bicycle class would provide the implementations for the methods that set and get retail price, assign a tracking number, and so on.

You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:
  • Capturing similarities among unrelated classes without artificially forcing a class relationship
  • Declaring methods that one or more classes are expected to implement
  • Revealing an object's programming interface without revealing its class
  • Modelling multiple inheritance, a feature that some object-oriented languages support that allows a class to have more than one 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
*/

Friday, 14 September 2012

Multiple Constructor Methods

A special type of method that creates an instance of a method is called a Constructor Method. When an object has member variables that are objects, we need to define a constructor method to set up those variables. We'll show how to do that here. If you want a more basic introduction to constructor methods, you may want to take a look at my prior article.

As an example, we're going to create a simple class of object for use with my simple video game kernel in a new version I'll be introducing in an article in the near future. The class definition consists mostly of constructor methods, since the class itself is presently not much more than a Rectangle with an added field.

import java.awt.*;

// A Simple class for use in the simple video game examples.
// Mark Graybill, Aug. 2010

public class Brick extends Rectangle{
 Color brickColor;

 public Brick(int newX, int newY, int newWidth, int newHeight){
  super(newX, newY, newWidth, newHeight);
  brickColor = new Color(0, 128, 255);
 }

 public Brick(int newX, int newY){
  this(newX, newY, 10, 10);
 }

 public Brick(){
  this(0,0,10,10);
 }

 public void setColor(Color newColor){ brickColor=newColor; }
 public Color getColor(){ return brickColor; }

} // End Brick

In this class, we have three forms of constructor, each with a different set of parameters. The one that takes the most parameters is the "base" version. It starts with a call to super(). This calls the constructor for Brick's superclass, or parent class, Rectangle. A look at the documentation for Rectangle shows that it has a constructor that takes four integer arguments, as we use here in super().

When we use super(), it must be the first thing we do within our constructor method. If we don't use super(), Java will do it automatically as the first thing in a constructor, calling it with no parameters. Since we want to set values for our inherited fields of x, y, width, and height it's better to call super() with those parameters. Otherwise, we could just as well have done something like this:

  public Brick(int newX, int newY, int newWidth, int newHeight){
  x=newX;
  y=newY;
  width=newWidth;
  height=newHeight;
  brickColor = new Color(0, 128, 255);
 }

This would have the same effect, and Java would insert an invisible call to super() in front of x=newX;.

The other constructors use the first method. To do this, they use another special method that's like super(). It's called this(), and it calls another constructor for this class. We can't do a call to Brick(), if we try, the compiler will see it as an undefined symbol:
>javac Brick.java 
Brick.java:11: cannot find symbol
symbol  : method Brick(int,int,int,int)
location: class Brick
    Brick(0,0,10,10);
    ^
1 error

So we use this() instead.

Like super(), the this() method must be the first thing called in the constructor method's body. Since don't call super()--it's in the base constructor--so there's no conflict about which goes first. If you use this(), you don't use super().

By using this() with the other constructor methods, we can keep all our key code code for the constructor in one place. If we had each constructor setting member values and constants without calling the base constructor method, then we'd end up with repeated code--a prime opportunity for bugs to enter our code if we update the code in one place, but not another. We don't want repeated code! Multiple independent constructors are used in the Java Tutorials, but I expect they're used to keep the lesson simple, not because they are a good coding practice!

You can find out more about this() and super() in the Java Language Specification, under Explicit Constructor Invocations.

You can probably see that I should really have my base constructor allow a Color to be passed to it, too. Try adding this yourself as an exercise to try out your understanding of constructor methods, then see what javac thinks of your work.

Java's Documentation: A Closer Look

I started discussing the place to look up Java's classes and methods in Java's Reference Manual and the place to look up the language's syntax and elements in The Java Language Manual. Here I'm going to take a deeper look at the documentation of Java's classes, interfaces, and so on in the the Java API Reference.

At first glance the page that's presented to you by the API reference can be overwhelming. Too much information!

First let's look at what's in each panel. If you don't have the API reference open in another tab or window of your browser, open it now. I'll be referring to what you see. The link is the Java API Reference. Bookmark it. Put it on your bookmark bar. Don't tattoo it on your forearm, though--there'll be a new URL when a new version of Java hits the streets and you'd be really embarassed to walk around with an old URL tattooed on your arm, wouldn't you? Writing it on a sticky and putting it on your monitor's bezel is probably good enough.

In the upper left frame, we have the list of packages. So far so good. If you know what package has what you're looking for in it, you can reduce the stuff listed elsewhere a lot by clicking on the name of the package. For example, JFrame is in javax.swing. If you click on javax.swing in the upper left frame, you'll see a change in the display. Now only the classes, interfaces, and enums and exceptions defined in javax.swing are listed in the lower left frame. It's a much smaller list to scroll through. If you don't know the package you're looking for, then you'll just have to go through the long list, which is in alphabetical order.

In the upper left frame, click on "All Classes" at the top of the list to list all the classes, interfaces, enums, and exceptions in the API again.

Once you find your class on the lower left, you'll get its documentation in the main panel on the right. This can be overwhelming as well. Since we've already talked about JFrame, let's look at it. Click on JFrame in the lower left panel. You can select javax.swing in the upper left panel first to make selecting JFrame easier if you wish.

In the main window, you'll see the big title "Class JFrame". Immediately above that in small type is the package it is in. If you didn't already know that JFrame is in javax.swing, now you would know. Remember the package for when you think you're going to look something up again later. Or, if you want to include a class and don't know what package to import, this is a good way to find out.

Beneath Class JFrame you'll see a list of other classes with little stairsteps leading down from one to another. These are the parent classes of JFrame, from the most basic object class in Java, java.lang.Object to JFrame itself. JFrame inherits from all these classes. Every method and field that they have, JFrame has, too.

You can see the documentation for any of them by simply clicking on the class's name. But don't just yet, we're going to look at more of JFrame's documentation first.

Next down the page is the list of interfaces that JFrame implements. This means that JFrame has the methods implemented in it that these interfaces call for. There's a lot more to an interface than this, but that's a subject for another time. In essence, JFrame inherits the functions of these interfaces by implementing the methods they define.

Below the line, we have a text description of JFrame headed by a pseudocode definition of JFrame. Some of these text descriptions in Java's API Specification are very useful, others are less useful. The one for JFrame is middle of the road. Like many descriptions, it comes in at the middle of the story, assuming that you have complete and perfect familiarity with some other part of Java that isn't what you're looking up here. This results in some look-ups turning into searches for the start of the story. You look up JFrame, it refers to Frame, then you go back to Window to understand what they're talking about in java.awt.Frame's documentation. Then you're reading all about java.awt.Component, and so on. Before you know it, you're looking at java.lang.Object and wondering what your original question was, and where all the time has gone.

So don't rely to heavily on these. Scan them, but if you're not getting what you want, keep moving down. Usually the later parts of the section are far more informative and direct. If there's some meta-information you're looking for on a class, check the related tutorial at Sun, or do a web search and look for a good intro or tutorial article. (You might even scroll down below my articles to where I keep a long index to my articles.)

I'm going to skip on down past the Nested Class Summary and list of nested classes inherited, too, and jump right into the Field Summary below them.

Fields are the variables and constants defined for the class. The first listed have been defined directly in this class. The listing tells you what they've been defined as, and their purpose. Following that is a list of ones inherited from each of the parent classes.

The Constructor Summary tells you what constructors are available for this class. If you were hoping for a JFrame constructor that lets you set it visible and give it a size right at the outset, you'll see you're out of luck. JFrame's constructors only allow you to define either or both of the JFrame's title and graphics configuration when it's instantiated (that is, when the Constructor makes a new one.) So you'll have to set the size and visibility later.

How you set size and visibility, and do a bunch of other things with a JFrame comes next. They're part of the Method Summary. First there's the list of methods defined in JFrame. These are the new methods that JFrame adds to its parents' methods. Each lists its type and name and parameter list along with a brief description. Following comes the long, long list of inherited methods. JFrames have all these methods, too, but their description lies in the document page for the class they were originally defined in. Click on their name to go there.

Following this come the detailed descriptions of JFrame's fields and methods. You could have gotten here the fast way by clicking on one of the field or method names in the summaries above. These are the real meat of the Java API specification. They tell you how to use the class methods, and what they do. Once you know them, the short description in the summary will usually be enough for you (if you need even that.)

Having the whole document hyperlinked makes it far more useful than a paper document would be. There'd just be too much page-flipping.

If you want to have a copy right on your own machine, you can download the entire thing. The PDF is available from Sun for Java 6, or you can get it for different versions from links on the Java SE reference page.

That way you don't have to be on the network all the time, or held hostage to the speed of your connection to look up something.