Home
Site Map
Useful Tools
Graphing Calc

Scientific Calculator
classs files

Types of Files

In Java

In C++

Method headers and implementation are in the same file and the class name must match the file name. Below is an example of partially functional Java Class. This class must be saved in a file name PrimeFactory.java
public class PrimeFactory{
	
//default constructor
public PrimeFactory(){;}
private int num;

public PrimeFactory(int aNum){
num = aNum;
}
	
public boolean isPrime(int num){
	for(int i=3;i <= Math.sqrt(num);i++)
	 if(num %i==0)
	 	return false;

return (num != 2);
}
	
	
}
	

The Java Runner class : Runner.java
public class Runner{

public static void main(String args[]){
PrimeFactory p = new PrimeFactory(5);
p.isPrime(5);
}
}


Method Headers and implementations should be saved in two distinct files. One file is the header file and has a '.h' extension such as PrimeFactory.h . This file is similar to a Java interface in that it specifies the method headers. The other file is the source code file and provides the 'code' that implements the header file. This file can have various extensions including '.c' and '.cpp' such as PrimeFactory.cpp.
The Header File PrimeFactory.h:
class PrimeFactory{
public:
bool isPrime(int num );


private:
int number;
};
A maor difference from Java Interfaces
You declare your private data members (fields and methods) in the header file.

The Source Code File PrimeFactory.C:
#include <iostream>
#include <math.h>
#include  "PrimeFactory.h"

using namespace std;

PrimeFactory::PrimeFactory(int n){
 number = n;
    }


bool PrimeFactory::isPrime(int num ){

int sq = (int)sqrt(num);
for(int i= 3;i <= sq;i++)
    if(num % i == 0)
        return false;
		

return (num != 2);
}


Points worth noting
1. In the source code file you must include the header file as in #include "PrimeFactory.h"

2. The syntax of writing methods is as follows:


returnType namespace:: methodName(paramaters){}
bool PrimeFactory:: myNewMethod(int anIntParamter){}

The Runner Class main.cpp

#include <iostream>
#include <math.h>
#include <string>
#include "PrimeFactory.h"

using namespace std;

int main() {

int num = 15;
PrimeFactory p(num);
bool r = p.isPrime(num);
 cout <<num << " is prime: ?  "<<   (bool)r  << endl;
  return 0;
}
Sitemap