java overriding not working - java

I'm a beginner in Java, I used PHP, C++ and Lua and never had this problem, I made two classes just for exercising's sake Facto and MyFacto, first one does find a factorial and the second one should find factorial not by adding, but by multiplying. Don't blame me for the stupid and pointless code, I am just testing and trying to get the hang of Java.
Main:
public class HelloWorld {
public static void main(String[] args) {
Facto fc = new Facto(5);
fc.calc();
System.out.println(fc.get());
MyFacto mfc = new MyFacto(5);
mfc.calc();
System.out.println(mfc.get());
}
}
Facto.java:
public class Facto {
private int i;
private int res;
public Facto(int i) {
this.i = i;
}
public void set(int i) {
this.i = i;
}
public int get() {
return this.res;
}
public void calc() {
this.res = this.run(this.i);
}
private int run(int x) {
int temp = 0;
if(x>0) {
temp = x + this.run(x-1);
}
return temp;
}
}
MyFacto.java:
public class MyFacto extends Facto {
public MyFacto(int i) {
super(i);
}
private int run(int x) {
int temp = 0;
if(x>0) {
temp = x * this.run(x-1);
}
return temp;
}
}
I thought the result should be 15 and 120, but I get 15 and 15. Why is that happening? Does it have something to do with calc() method not being overriden and it uses the run() method from the Facto class? How can I fix this or what is the right way to override something like this?

The reason you're running into issues is due to member access visibility.
In a nutshell:
public allows any Java class to see the field/function, so long as it can be reached.
<package>, or no apparent modifier, allows any Java object (but not subclasses) to see the field/function, as long as they're in the same directory, or package.
protected allows the declared class and all other subclasses to access that field/function, as well as any class in the same directory/package.
private allows only the declared class to access that field/function.

To expand on what #Makoto said, you're running into an issue because the calc() method of Facto does not have access to the run() method of MyFacto, so it's using it's own run() method. Changing them both to protected instead of private should do the trick.
Also, something you should probably learn to use is the #Override annotation. It's good practice to put it above any method that you are overriding. That way, if you misspell something, or the parameters don't match, you will get a warning. Also, it makes it clear to you and/or the reader. For example:
MyFacto.java#run:
#Override
protected int run(int x) {
int temp = 0;
if(x>0) {
temp = x * this.run(x-1);
}
return temp;
}
Good luck with Java!

Related

How can i call the method from another class?

Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.

intellij idea structural search and replace - find all methods that call an api

I'm trying to find all methods in a large java project in which a specific static api is called, and then add an annotation those methods.
The methods can have arbitrary complexity. It can be a simple MyAPI.method("foo");, but it can be also try(Int result = MyAPI.AnotherMethod("foo")) { }. It can be nested inside of a code block, in a lambda expression, anywhere.
The best I have been able to create is this:
class $_1$ {
$ReturnType$ $Method$ /* count 1 to inf */ ($ParameterType$ $Parameter$ /* count 0 to inf */)
{
$stmt1$; /* count 0 to inf */
MyAPI.$MethoddCall$($param$ /* count 0 to inf */);
$stmt2$; /* count 0 to inf */
}
}
This finds some usages, but generally only the simplest one. In the example class bellow, it finds only usage1 (a,b,c) and usage5. Other examples are skipped. Is it even possible to write such a general search, or would I need to tailor it to all possible cases?
The point is, the api is used in thousands of methods and every and each has to be annotated, so I'm looking for anything that will mean I don't have to do it by hand. Worst case, I would try luck with awk, but that would mess up with the crazy CVS we are using, so I prefer Idea solution.
Now an example:
import java.io.PrintWriter;
public class SearchAndReplaceTest
{
private static class MyAPI
{
public static void foo(String x)
{}
public static int bar(String x)
{
return 1;
}
public static int baz(String x, int y)
{
return 1;
}
public static PrintWriter guu(String x)
{
return null;
}
}
public void usage1a()
{
MyAPI.foo("aaaa");
}
public void usage1b()
{
MyAPI.baz("aaaa", 1+1);
}
public void usage1c()
{
MyAPI.baz("aaaa", (1+1)-1);
}
private static int usage2(String xxxx) throws Exception
{
new String();
if(MyAPI.bar("x") == 1)
{}
return 0;
}
private void usage3a(String xxxx) throws Exception
{
new String();
if(1 == 1)
{
MyAPI.baz("xxx", (10+3) - 1);
}
}
private void usage3b(String xxxx) throws Exception
{
new String();
if(1 == 1)
{
MyAPI.foo("xxx");
}
}
private static void usage4(String xxxx) throws Exception
{
new String();
try(PrintWriter x = MyAPI.guu("x"))
{}
catch (Exception e){}
}
public void usage5()
{
new String();
MyAPI.foo("aaaa");
if(1==0)
{}
}
}
I have found out how to do it. Rather than trying to utilize Structural Search's power, I have to search the body of a function only by a script. So the search is for:
class $_1$ {
$ReturnType$ $Method$ ($ParameterType$ $Parameter$);
}
With those constraints:
$Parameter$ // count: [0, inf]
$Method$ // count: [1, inf], text: [x] within hierarchy, script: Method.getText().contains("MyAPI")

Please Explain Java 8 Method Reference to instance Method using class name

public interface MyFunc<T> {
boolean func(T v1, T v2);
}
public class HighTemp {
private int hTemp;
HighTemp(){
}
public HighTemp(int ht) {
this.hTemp = ht;
}
boolean sameTemp(HighTemp ht2){
return hTemp == ht2.hTemp;
}
boolean lessThanTemp(HighTemp ht2){
return hTemp < ht2.hTemp;
}
}
class InstMethWithObjRef {
static <T> int counter(T[] vals, MyFunc<T> f, T v){
int count = 0;
for (int i = 0; i < vals.length; i++) {
if(f.func(vals[i], v)) count++;
}
return count;
}
public static void main(String[] args) {
int count;
//Create an array of HighTemp objects.
HighTemp[] weekDayHighs = {new HighTemp(89), new HighTemp(82),
new HighTemp(90), new HighTemp(89),
new HighTemp(89), new HighTemp(91),
new HighTemp(84), new HighTemp(83)};
count = counter(weekDayHighs, HighTemp::lessThanTemp,new HighTemp(89));
System.out.println(count);
}
}
Please explain how
boolean sameTemp() is compatible with func() in Functional interface.
sameTemp() method got implemented on func() in Functional Interface.
count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89)); is working
Please Explain All points separately.
Equivalent lambda expression of HighTemp::lessThanTemp is
(highTemp1, highTemp2) -> {
return highTemp1.lessThanTemp(highTemp2);
}
This is one of the features of Java8 named Reference to an Instance Method of an Arbitrary Object of a Particular Type
Consider following example,
interface FIface<T> {
int testMethod(T a, T b);
}
class Test2 {
private String str;
Test2(String str) {
this.str = str;
}
int ok(Test2 test2) {
System.out.println("Currnet String : "+ this.str);//Refer to t1
System.out.println("Test String : "+test2.str);//Refer to t2
return 0;
}
}
public class Test {
public static <T> int checkCall(T t1, T t2, FIface<T> fiFace) {
//Here Test2 :: ok is equivalent to t1.ok(t2)
return fiFace.testMethod(t1, t2);
}
public static void main(String[] args) {
checkCall(new Test2("a"), new Test2("b"), Test2 :: ok);
}
}
OUTPUT
Currnet String : a
Test String : b
Note here that Test2 :: ok is valid for the call even ok method is not static.
When you call the method checkCall for the functional interface you still have two arguments which are t1 and t2 and for that valid lambda expression can have parameters as (Test t1, Test t2) so your method Test2 :: ok here becomes valid for the call. Internally it works this way t1.ok(t2).
So, fiFace.testMethod(t1, t2); will will invoke method as t1.ok(t2)
For starters I'm not a professional programmer. I too had a great difficulty in understanding the so called "Reference to an Instance Method of an Arbitrary Object of a Particular Type" I think this might be helpful for somebody who comes here from a google search.
I understood it a little bit with the help of lambda expressions.
In your code HighTemp::lessThanTemp as a Lambda expression would look like (x,y)->{x.lessThanTemp(y);} Replacing the method reference with this lambda expression would produce the same result. The above Lambda expression or the method reference both tell the interface method what to do.
When you use the method reference it tells the interface method to use the referred method from the given class, to carryout its function. Therefore if you convert HighTemp::lessThanTemp to English words it would sound something like "implement the lessThanTemp method form the class HighTemp as the implementation of the interface function". As you might've noticed in that case the return types and the argument types should be compatible. Otherwise you cannot implement an interface.
I would provide you another simple example code. More examples helps to understand this concept.
interface myint{
int returnit(Test t ,int y);
}
class Test{
int x=0;
public Test(int x){
this.x=x;
}
public int addNumbers(int y){
return x+y;
}
public int subtractNumbers(int y){
return x-y;
}
}
public class myclass{
private static void myMethod(Test t,myint inf,int y){
int x=inf.returnit(t, y);
System.out.println(x+"");
}
public static void main(String[] args){
myMethod(new Test(4),Test::addNumbers,7);
myMethod(new Test(4),Test::subtractNumbers,7);
}
}
Output would be:
11
-3
This is the simplest way I could imagine it. See how return types and argument types gets matched using the above sentence pattern. Spend some time on it.
This is the Interface
package learninglambdaexp;
#FunctionalInterface
public interface TempInterface {
public boolean validTemp(Temperature temp);
}
This is the class
package learninglambdaexp;
public class Temperature {
private int temp;
public Temperature(int temp) {
this.temp = temp;
}
public boolean isEvenTemp() {
return temp % 2 == 0;
}
public boolean isOddTemp(){
return !isEvenTemp();
}
}
This is the Class with the Main Method
package learninglambdaexp;
import java.util.ArrayList;
import java.util.List;
public class AnotherMainClass {
public static void main(String[] args) {
List<Temperature> tempCollection = new ArrayList<>();
tempCollection.add(new Temperature(100));
tempCollection.add(new Temperature(20));
tempCollection.add(new Temperature(30));
tempCollection.add(new Temperature(40));
tempCollection.add(new Temperature(50));
tempCollection.add(new Temperature(60));
tempCollection.add(new Temperature(70));
int k1 = countVariation(tempCollection, Temperature::isEvenTemp);
//int k2 = countVariation(Temperature::lowTemp);
System.out.println(k1);
// System.out.println(k2);
}
private static int countVariation(List<Temperature> tempCollection, TempInterface ti) {
int count = 0;
for (Temperature eachTemp : tempCollection) {
if (ti.validTemp(eachTemp)) { // (eachTemp) -> {return eachTemp.isEvenTemp();};
count++;
}
}
return count;
}
}
With one argument its easier to understand
Please, correct me if I am wrong, but the way I think about this type of method references (Reference to an Instance Method of an Arbitrary Object of a Particular Type) is that when we pass a method reference, in this case to the counter method, the instance of anonymous class which implements MyFunc interface is created. Then, inside this anonymous class, we override func method which is passed two parameters. And then inside the func method, lessThanTemp method is called like this:
v1.lessThanTemp(v2);
So for me this concept looks something like this:
public class Demo {
public static void main(String[] args) {
AnonymousClass an = new AnonymousClass();
System.out.println(an.apply(new SomeClass(3), 4));
}
}
interface SomeInterface {
int apply(SomeClass obj, int n);
}
class SomeClass {
private int n;
SomeClass(int n) {
this.n = n;
}
int add(int n) {
return this.n + n;
}
}
class AnonymousClass implements SomeInterface {
#Override
public int apply(SomeClass o, int n) {
return o.add(n);
}
}

How to get value of variable from other class?

I have a public integer variable (MainReg) in my Counter Class. I want to get value of this variable and set it in my JComponent class. Here is piece of my JComponent class:
public class Komponent2 extends JComponent implements ActionListener
{
Counter counter3;
.
.
.
int a = counter3.valueOf(MainReg);
But it doesn't work. I tried also:
int a = valueOf(counter3.MainReg);
int a = counter3.valueOf(counter3.MainReg);
int a = counter3.MainReg;
But it still doesn't work. How can I get this variable? Thanks for helping me.
EDIT
Here is my Counter class:
import java.util.Observable ;
public class Counter extends Observable
{
public int MainReg;
public int CompareReg;
public Mode countMode;
public boolean OVF;
private int a=0;
public Counter()
{
OVF=false;
}
public void setCompareReg(int dana)
{
CompareReg=dana;
}
public void setMainReg(int dana2)
{
MainReg=dana2;
}
public void setMode(Mode countMode)
{
this.countMode=countMode;
}
public void Count()
{
if (countMode==Mode.UP)
{
MainReg++;
OVF=false;
if (CompareReg < MainReg)
{
OVF=true;
MainReg=0;
setChanged();
notifyObservers();
}
}
else if (countMode==Mode.UPDOWN)
{
if(MainReg >= CompareReg)
{
a=MainReg;
MainReg--;
OVF=true;
}
else
{
if(MainReg >= a)
{
MainReg++;
OVF=false;
}
else
{
MainReg--;
if(MainReg==0)
{
a=0;
}
OVF=false;
}
}
}
else if (countMode==Mode.CONTINOUS)
{
MainReg++;
OVF=false;
if (65536 < MainReg)
{
MainReg=0;
OVF=true;
}
}
}
}
Well I see two ways you can do this.
Your MainReg integer is public, you could simply use int i = counter3.MainReg;
Or you could create a getMainReg() method in your Counter class. Then call it from whatever class.
EX:
public int getMainReg() {
return this.MainReg;
}
Give your Counter class getter methods, and then call them when you need to access their values. i.e.,
public int getMainReg() {
return mainReg;
}
public int getCompareReg(){
return compareReg;
}
public Mode getCountMode() {
return countMode;
}
And make your fields all private. Also your code should obey Java naming rules: variable names should begin with lower-case letters.
Also be sure that you've initialized your counter variable in the class that uses it, either by creating a new instance, or if appropriate, passing in a valid instance in a constructor or method parameter.

How to inherit static field and change it's value?

I'm working on program/game where I have static utility class with params.
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static int MAX_SCORE = 1000;
...
}
then I need to override this values in some specific cases, for example playing on map with limited score. So I did following:
class ParamsLimited extends ParamsGeneral {
public static int MAX_SCORE = 500;
// other params stay same
}
And the intended usage is following:
class Player {
ParamsGeneral par;
public Player() {
if(onLimitedMap()){
par = new ParamLimited();
}
}
public boolean isWinner() {
if(this.score == par.MAX_SCORE) {
return true;
}
return false;
}
}
I haven't actually tested this code, because IDE is complaining about calling static field through instance and also about field hiding. I clearly see that this code is stinks, so is there a way to achieve this or do I have to write each param class separately?
PS: I know I shoud make the default class abstract and use getters, I'm just curious if there is a way to make the values accesible statically.
You cannot override static members - in Java, neither methods nor fields could be overriden. However, in this case it does not look like you need to do any of that: since you have an instance of ParamsGeneral in the par variable, a non-static method would do what you need with the regular override.
class ParamsGeneral {
public int getMaxScore() {
return 1000;
}
}
class ParamsLimited extends ParamsGeneral {
#Override public int getMaxScore() {
return 500;
}
}
...
public boolean isWinner() {
// You do not need an "if" statement, because
// the == operator already gives you a boolean:
return this.score == par.getMaxScore();
}
I wouldn't use subclassing for a general game vs a limited game. I would use an enumeration, like:
public enum Scores {
GENERAL (1000),
LIMITED (500),
UNLIMITED (Integer.MAX_INT);
private int score;
private Scores(int score) { this.score = score; }
public int getScore() { return score; }
}
Then, when constructing a game, you can do:
Params generalParams = new Params(Scores.GENERAL);
Params limitedParams = new Params(Scores.LIMITED);
And so forth.
Doing it this way allows you to change the nature of your game while keeping your values centralized. Imagine if for every type of parameter you think of you have to create a new class. It could get very complicated, you could have hundreds of classes!
Simplest solution is to do this:
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static final int MAX_SCORE = 1000;
public static final int MAX_SCORE_LIMITED = 500;
...
}
class Player {
int maxScore;
public Player() {
if(onLimitedMap()){
maxScore = ParamsGeneral.MAX_SCORE_LIMITED;
}
else {
maxScore = ParamsGeneral.MAX_SCORE;
}
}
public boolean isWinner() {
if(this.score == this.maxScore) {
return true;
}
return false;
}
}
No need to have an instance of ParamsGeneral, it is just a collection of static definitions for your game.
Have MAX_SCORE be private static with public static getters; then you can call ParamsGeneral.getMaxScore and ParamsLimited.getMaxScore and you'll get 1000 and 500 respectively

Categories