Inheritance issue that i cannot understand - java

I have this 2 classes:
public class A {
protected int _x;
public A() {
_x = 1;
}
public A(int x) {
_x = x;
}
public void f(int x) {
_x += x;
}
public String toString() {
return "" + _x;
}
}
public class B extends A {
public B() {
super(3);
}
public B(int x) {
super.f(x);
f(x);
}
public void f(int x) {
_x -= x;
super.f(x);
}
public static void main(String[] args) {
A[] arr = new A[3];
arr[0] = new B();
arr[1] = new A();
arr[2] = new B(5);
for (int i = 0; i < arr.length; i++) {
arr[i].f(2);
System.out.print(arr[i] + " ");
}
}
}
The output is 3 3 6 and I am wonder why the third iteration is 6

The constructor:
public B(int x)
{
super.f(x);
f(x);
}
is translated by the compiler to this:
public B(int x)
{
super();
super.f(x);
f(x);
}
I guess now you would understand, why it's 6.

Related

How to access local variable in Anonymous class?

interface Interf {
void m1();
}
public class Test {
int x = 888;
Interf f;
public void m2() {
Integer x = 777;
f = new Interf() {
Integer x = 666;
public void m1() {
int x = 555;
System.out.println(x);
System.out.println(this.x);
}
};
}
public static void main(String[] args) {
Test t = new Test();
t.m2();
t.f.m1();
}
}
How can I access x variable with value 777 inside m1() method(In Anonymous class) with same name? Is it possible to access?
No, because it is shadowed. But you can change the name (and no need for Integer, int will suffice).
public void m2() {
int y = 777;
f = new Interf() {
int x = 666;
public void m1() {
int x = 555;
System.out.println(x);
System.out.println(this.x);
System.out.println(y);
}
};
}
Outputs
555
666
777

Genetic algorithm Java, passing functions with two coordinates

I've written my first Genetic Algorithm in Java and I'm able to optimize functions with one argument x, but I don't know how to optimize functions with two arguments x and y. Algorithm class and main app works correctly so i send only Individual.java and Population.java. If I think correctly in genes I have only x-coordinate but I'm not sure how to add y-coordinate. Any advise will be helpfull.
Individual.java
public class Individual {
private int[] genes;
private int fitness;
private Random randomGenerator;
public Individual() {
this.genes = new int[Constants.CHROMOSOME_LENGTH];
this.randomGenerator = new Random();
}
public void generateIndividual() {
for(int i = 0; i < Constants.CHROMOSOME_LENGTH; i++) {
int gene = randomGenerator.nextInt(2);
genes[i] = gene;
}
}
public double f(double x) {
// return Math.pow(x,2);
return (Math.pow((1-x),2)) + (100*(Math.pow((1-Math.pow(x,2)),2)));
// return Math.sin(x)*((x-2)*(x-2))+3;
}
public double getFitness() {
double genesToDouble = genesToDouble();
return f(genesToDouble);
}
public double getFitnessResult() {
double genesToDouble = genesToDouble();
return genesToDouble;
}
public double genesToDouble() {
int base = 1;
double geneInDouble = 0;
for( int i =0; i < Constants.GENE_LENGTH; i++) {
if(this.genes[i] == 1)
geneInDouble += base;
base = base*2;
}
geneInDouble = (geneInDouble / 1024) * 10.1;
return geneInDouble;
}
public int getGene(int index) {
return this.genes[index];
}
public void setGene(int index, int value) {
this.genes[index] = value;
this.fitness = 0;
}
}
Population.java
public class Population {
private Individual[] individuals;
public Population(int populationSize) {
individuals = new Individual[populationSize];
}
public void initialize() {
for(int i = 0; i < individuals.length; i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
}
public Individual getIndividual(int index) {
return this.individuals[index];
}
//maksimum lub minimum
public Individual getFittestIndividual() {
Individual fittest = individuals[0];
for(int i =0; i < individuals.length; i++) {
if(getIndividual(i).getFitness() < fittest.getFitness())
fittest = getIndividual(i);
}
return fittest;
}
public int size() {
return this.individuals.length;
}
public void saveIndividual(int index, Individual individual) {
this.individuals[index] = individual;
}
}

How can I receive result of factorial to another class?

The problem is to receive the result of previous calculations.
public class FactorialArray {
public static long[] factorial = new long[21];
public static int fact = 0;
static {
factorial[0] = 1;
}
public static long factorial(int x) {
while (fact < x) {
long element;
factorial[fact] = element.getFact(element);
fact++;
}
return factorial[x];
}
And here it is a class where I calculated factorial:
public class Factorial {
private long factorialCalculator(int x){
if(x==0 || x==1)
return 1;
else
return (long)x*factorialCalculator(x-1);
}
public long getFact(int x){
return factorialCalculator(x);
}
}
public static long [] factorial(int x) {
Factorial factObj = new Factorial();
while (fact < x) {
long element;
factorial[fact] = factObj.getFact(fact);
fact++;
}
return factorial;
}
static class Factorial {
private long factorialCalculator(int x) {
if (x == 0 || x == 1)
return 1;
else
return (long) x * factorialCalculator(x - 1);
}
public long getFact(int x) {
return factorialCalculator(x);
}
}

<Variable> Cannot Be Resolved to Variable

I have the following code:
public interface CarInterface {
int getCapacity();
String getCarRegistration();
void setCarRegistration(String registration);
int getFuelAmmount();
boolean isFull();
boolean isRented();
int addLitres(int litres);
int drive();
}
public abstract class Car implements CarInterface{
protected boolean full;
private boolean rented;
private String registration;
protected int fuel;
public String getCarRegistration() {
return registration;
}
public void setCarRegistration(String registration){
this.registration = registration;
}
public int getFuelAmmount() {
return fuel;
}
public boolean isFull() {
return full;
}
public boolean isRented() {
return rented;
}
}
public class LargeCar extends Car{
public int drive() {
return getFuelAmmount();
}
public int addLitres(int litres) {
fuel = fuel + litres;
if (fuel > 65) {
fuel = 65;
}
if (isRented()) {
int x = 5;
}
return x;
}
public int getCapacity() {
return 65;
}
}
Eclipse tells me that the return type is incompatible with the interface declaration (The return type is incompatible with
CarInterface.addLitres(int)). I have no idea why this is. I said I'd return an int in the interface, and that's what I'm doing...
It also has a problem with 'x', which it says cannot be resolved to a variable. Oddly enough, when I take "int x" out of the if statement, the error message disappears.
You have to declare x outside the if.
int x = 0;
if (isRented()) {
x = 5;
}
This here:
public int addLitres(int litres) {
fuel = fuel + litres;
if (fuel > 65) {
fuel = 65;
}
if (isRented()) {
int x = 5;
}
return x;
}
is invalid since the variable x is in a limited scope just because is declared inside a if segment...
do instead: declare the int x as a variable in the method and set its corresponding value if fuel or whatever you need to chec
example:
public int addLitres(int litres) {
int x = 0;
fuel = fuel + litres;
if (fuel > 65) {
fuel = 65;
}
if (isRented()) {
x = 5;
}
return x;
}
Well, you can't return x because it's not in scope to be returned since it is declared inside of the if(isRented()){int x = 5} code block. To return x you have to define it outside of the if(isRented()){int x = 5} scope like so
int x = 0;
if(isRented())
{
x = 5;
}

Composing Function interfaces in Java

interface PairFloatFunction {
Pair<Float,Float> calculate(int x);
}
interface FloatFunction {
float calculate(int x);
}
class SQRT implements PairFloatFunction {
public Pair<Float, Float> calculate(int x) {
return new Pair(-pow(x,0.5), pow(x,0.5))
}
}
class ADD_ONE implements FloatFunction {
public Float calculate(int x) {
return x + 1;
}
}
I would like to compose to functions so that I can perfom this:
ADD_ONE(SQRT(100)) = Pair(-9,11)
I understand i need to 'glue' the functions together.
but I am stuck here, should I be writing another method overload that does this?
class ADD_ONE {
public Float calculate(int x) {
return x + 1;
}
public Float calculate(Pair pair) {
pair.first += 1;
pair.second += 1;
return pair
}
}
Sorry I am new to functional programming, is there a nice solution to this?
Based on your code above, I would create a generic interface which will be responsible for calculating.
interface Calculation<T> {
T calculate(int x);
}
This is a Java 7 implementation, because you did not specify Java 8.
Further Explanation
The return type T is generic; meaning that your implementation can return any Object type but it must consume an integer x. You could even make the x parameter generic so that you can decide what function will take as a parameter type.
Note: The static classes would be moved into their own class files and the static modifier should be removed. I only did this to consolidate everything for the sake of brevity.
Full Example
public class Functional {
static interface Calculation<T> {
T calculate(int x);
}
static class Sqrt implements Calculation<Pair<Float, Float>> {
public Pair<Float, Float> calculate(int x) {
float root = (float) Math.pow(x, 0.5);
return new Pair<Float, Float>(-root, +root);
}
}
static class AddOne implements Calculation<Float> {
public Float calculate(int x) {
return (float) (x + 1);
}
}
static <T> T calculate(int x, Calculation<T> calculation) {
return calculation.calculate(x);
}
public static void main(String[] args) {
Calculation<?>[] calculations = { new Sqrt(), new AddOne() };
int x = 49;
for (Calculation<?> calculation : calculations) {
System.out.printf("%s: %s%n",
calculation.getClass().getSimpleName(),
calculate(x, calculation));
}
}
static class Pair<T, U> {
private T val1;
private U val2;
public Pair(T val1, U val2) {
this.val1 = val1;
this.val2 = val2;
}
protected T getVal1() {
return val1;
}
protected void setVal1(T val1) {
this.val1 = val1;
}
protected U getVal2() {
return val2;
}
protected void setVal2(U val2) {
this.val2 = val2;
}
#Override
public String toString() {
return "(" + val1 + ", " + val2 + ")";
}
}
}
Output
Sqrt: (-7.0, 7.0)
AddOne: 50.0

Categories

Resources