Java - inheritance, class with methods - java

I have my subclass:
public class Actions extends Main{
public void getFireTarget() {
GameObject target = getGameObjects().closest("Target");
do{
log("Shooting at the target");
getMouse().click(target);
} while(target != null && !getDialogues().inDialogue() && getLocalPlayer().getTile().equals(rangeTile));
}
}
I want to write similar methods, so I can call them in my Main class, so I don't have to write over and over.
My main class looks like this (won't fully paste it as it's long):
public class Main extends AbstractScript{
...code here
Actions actions = new Actions();
}
So I am trying to implement the methods in Actions by doing actions.getFireTarget(), which seems to work. But when I compile, I am getting two compile errors:
1) In the Main class, in the line: Actions actions = new Actions();
2) In the Actions class, in the line where I am extending the superclass.
Am I missing something in the sub class in order to store methods and then call them in the main method? Please advise! Thanks

The syntax is wrong. () are not allowed here: public class SomeName(). Remove the brackets.

I am having trouble understanding your details.
Here is a short info about inheritance:
public class A{
protected int t;
public void methodA(){}
}
public class B extends A{
#Override
public void methodA(){}
public void methodB(){}
}
If you override the methodA in class B, any call from a instance of class B to the method will use the method defined in class B. (If you dont write the method in class B, it will use the method from class A)
Objects of class A cannot use methodB() defined in class B.
Also you can access the field t in class B, because of the protected modified.

I think its better for you your problem to instantiate other class to your main class if you have same function name or same variable name. try to compile and run this code
public class First{
Second sec = new Second();
String s = "This is first";
public First(){
System.out.println(this.s);
System.out.println(getSecondString());
System.out.println(sec.getSecondString());
}
public String getSecondString(){
return "This is first";
}
public static void main(String args[]){
new First();
}
}
public class Second {
String s = "This is second";
public String getSecondString(){
return s;
}
}

Related

ambiguity in invoking a method inherited from another class

I have two java class files
Hi.java which belongs to second package
package second;
public class Hi {
protected int v=20;
protected void m(){
System.out.println("i am protectTED");
}
}
S.java which belong to first package
package first;
import second.Hi;
interface i1
{
void m();
int a=200;
}
interface i2{
void m1();
int b=100;
}
class S extends Hi implements i1,i2
{
int a=50;
public void m()
{
System.out.println("hi");
}
public void m1()
{
System.out.println("hello");
}
public static void main(String[] args) {
S s=new S();
/*need correction here (i don't know the exact syntax to mention to get
the desired output)
s.m(); //should invoke method m() from class Hi only.
s.m(); //Should invoke method m() from class S only.
*/
//the following statements prints the desired values
s.m1();
System.out.println(s.v);
System.out.println(i1.a);
System.out.println(s.a);
System.out.println(b);
}
}
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
How to differentiate the 2 methods for invoking. Is it even possible?
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
Correct, because you've overridden it with m in S. Overriding methods is fundamentally different from overriding fields. (And in general, it's best to avoid overriding any fields that are visible to your subclass, as you're doing with a.)
In instance code in S, you can run the inherited m via super: super.m(). But you cannot do that from static code, not even static code in S. You could give yourself a private callSuperM in S:
private void callSuperM() {
super.m();
}
...and then use that in main:
s.callSuperM(); // "i am protectTED"
s.m(); // "hi"

Use method from other class like native methods?

(newbie in Java) I couldn't find exactly this question on SO. I have project, with two files (phseudo-code):
First Java File (class)
public class A {
public void xyz() { System.out.println("hello");}
}
Second Java File (class)
public class B Extends ZZZZZ {
public void callme() {
xyz(); // <----------------- I want to call in this way, but It cant be done like this.
}
}
How to make xyz() to call successfully (like as if was defined inside b() class natively !!).
p.s. again, I don't want to call it with classname in front, like this:
a.xyz();
The whole idea of instance methods, like xyz is in this, is that you are using the state of an instance of A in the method, without having to pass that instance as an argument like this:
... String xyz(A thisInstance, ...) {...}
Instead you use:
A thisInstance = ...;
thisInstance.xyz(...);
That's why you need an instance of A, because it is practically an argument to the function.
However, if you don't need an instance of A, you can make the method static:
static String xyz(...) {...}
Then you can call it without passing an instance of A:
A.xyz(...);
You can use a static import so that you don't have to write A:
import static A.xyz;
...
xyz(...);
Okay several possibilities:
Instantiate A:
A a=new A();
a.xyz();
(you do not want this)
Heredity:
public class B extends A {...}
and
public class A extends ZZZZZ{...}
so you can still extend ZZZZZ;
Interface:
public interface A{...}
public class B extends ZZZZZ implements A{...}
Static Method:
public class A{
public static void xyz()
{
System.out.println("hello");
}
}
public class B{
public void callme()
{
A.xyz());
}
}
This will help you.
class A {
public void xyz() {
System.out.println("hello");
}
}
class ZZZZZ extends A{
}
class B extends ZZZZZ {
public void callme() {
xyz();// <----------------- calling this shows error
}
}

android accessing object inside extended class

I have some problems using this keyword. If I have a couple of classes implementing another class, how can I use their values without calling the class itself? I explain.
//this is my first class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
//getter/setter below
}
//this is my second class
public class Foo2 extends FooHelper{
public double fooDouble;
public float fooFloat;
}
//this is my main method, i'm using it for calling the value.
//I omit all the thrash code before.
//This is how i want to call the method:
//imagine before there are onCreate, activity,...
Foo foo = new Foo().GetFooInt();
//this is the class extended from the firsts
public class FooHelper{
public void GetFooInt(){
//here is my problem, i need to call the Foo class and the fooInt value.
//I want also to be able to edit the Foo object, for example:
if(((Foo)this).getFooInt() == 0){
(Foo) this.setFooInt(5);
}
}
}
This is what i want to achieve, acces a class which extends another class with the only this keyword from the extended class. How can I do it?
EDIT:
I badly explained i think.
My problem is that i want to access my Foo object inside the FooHelper, not FooHelper's method inside Foo object.
Example:
after using this code:
Foo foo = new Foo();
foo.HelperClassMethod();
I need (in HelperClass) to access Foo object which invoked it.
public HelperClass<Foo> {
public void HelperClassMethod(){
//HERE i need to use the "foo" object which invoked this method
}
}
I added the <Foo>, probably I was missing it, is this correct? and how can i use this foo object in the method from the helper class? thanks all
EDIT2: i totally failed on my question i thinkm lets ignore the above code and just check below:
I Have to access an object inside the extended class's method.
I have this class:
public class Foo extends FooToExtend{
public int fooInt;
}
the class which is extended is this:
public class FooToExtend{
public void MethodOne(){
//HERE i need to access the calling object
}
}
now, in my main activity, I want to do this:
Foo foo = new Foo();
foo.MethodOne();
My doubt is how i can access foo object i created in main inside my MethodOne.
I have to change my FooToExtend in
public class<Foo> FooToExtend{
...
}
but I don't still know how to access the foo object inside it.
I see 2 problems here, understanding this keyword, and extending clases
PROBLEMS WITH this KEYWORD
Imagine you have a class and you are executing some code: keyword this refers to the class itself, if you where the object this would be the equivalent to me. Check here and here longer explanations, examples and tutorials.
PROBLEMS WITH extend
Also you must extend from top (interfaces or abstract classes) to bottom (extended) classes and implement in bottom part:
//this is the PARENT (FIRST) class extended from the CHILDREN (SECOND)
public abstract class FooHelper{
public abstract void GetFooInt();
}
//this is the CHILD (SECOND!!!) class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
#Override
public void GetFooInt() {
// are you sure you getFooInt method can return a null???
if(this.getFooInt() == null){
this.setFooInt(5);
}
//getter/setter below
}
EDIT 1
Oh ok, this was useful. one more question, a way is to use abstract, as you said, but is there a way to do the same without implementing it all times? just for info, my objective is to use Foo.FooHelperMethod() and be able in "FooHelperMethod()" to access Foo class. I hope i explained it, i don't know how to do it.. if it's impossible i will use abstract as you suggested :)
Sure, this is inheritance, simply don't declare abstract the parent, and implement the methods AND the attributes there, all the children will have this methods and attributes by extending the parent class.
Lets see this example:
//this is the PARENT (FIRST) class extended from the CHILDREN (SECOND)
class FooHelper {
int theIntCommonValue;
public int getTheIntCommonValue() {
return theIntCommonValue;
}
public void setTheIntCommonValue(int theIntCommonValue) {
this.theIntCommonValue = theIntCommonValue;
}
}
// CHILDREN CLASS, look how calling this.getTheIntCommonValue() (the parent method)
// doesn't throw any error because is taking parent method implementation
class Foo extends FooHelper {
public void getFooInt() {
if (this.getTheIntCommonValue() == 0)
this.setTheIntCommonValue(5);
}
}
class Foo2 extends FooHelper {
public void getFooInt() {
if (this.getTheIntCommonValue() == 3)
this.setTheIntCommonValue(8);
}
}
EDIT2:
My doubt is how i can access foo object i created in main inside my MethodOne.
ANSWER:
Passing the object as a parameter. But then, you need static class, not an extended one, lets see an
EXAMPLE:
Foo.java
public class Foo {
public int fooInt;
}
FooHelper.java
public static class FooHelper {
public static void methodOne(Foo foo){
//HERE i need to access the calling object
// for example, this?
if (foo.fooInt == 2)
}
}
Now, how do you execute it?
Main.java
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
FooHelper.methodOne(foo);
}
NOTES
conventions say, methods in java start in LOWECASE and class name starts in UPPERCASE.
you must put both classes in sepparated files in order to allow static public class
I'm not sure I completely understand. But it looks as though you want GetFooInt to perform something differently depending on the class that extended it. So I think the best here to check the instanceof.
public class FooHelper{
public void GetFooInt(){
if(this instanceof Foo)
{
((Foo) this).fooInt = 5;
}
}
}
By the situation you want to named one class "Helper" I assume you will use it as a helper-class.
public class Helper {
public static int screenHeight = 500;
}
public class AnyOtherClass {
testSomething() {
System.out.println(Helper.screenHeight);
Helper.screenHeight = 510;
System.out.println(Helper.screenHeight);
}
}
For some basic understanding: this is the keyword you use in a non-static context to access the variables and methods of the Object you're currently inside. Proper use of this example:
public class SomeClass {
private int someInt;
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
In this example the this is necessary because the local variable (/parameter) someInt has the same name as the global class variable someInt. With this you access the class varaible of the Object you're "in".
Example of unnecessary use of this:
public class SomeClass {
private int someInt;
public int squareSomeInt() {
return this.someInt * this.someInt;
}
}
Here you don't need the keyword this since there is no local variable called someInt.
On the other hand super is a keyword which accesses the variables and methods of the parent class (the class, your class is derrived from). Example:
public class SomeClass {
private int someInt;
public int squareSomeInt() {
return someInt * someInt;
}
}
the derrived class:
public class Other extends SomeClass {
public int squarePlusSquare() {
return super.squareSomeInt() + super.squareSomeInt();
}
}

Overriding method with a lower-visibility one results in compilation error

I have one class and one interface:
public interface A {
public void getNum();
}
public class B {
public void getNum() {
System.out.println("4");
}
}
public class C extends B implements A {
protected void getNum() {
System.out.println("3");
}
}
Now my question is, why this code is giving compilation error and how can we avoid it. Is there any way in which we can override this method in class C?
From Java Language Specification:
jls-8.4.8.3
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
...
Notice that you are trying to override public method getNum() inherited from class B (and also from interface A) with new one that has protected access modifier. It means that you are trying to reduce visibility of this method which according to specification is incorrect.
To be able to override this method you need to use public access modifier with your new version of that method.
Why you cant reduce visibility? Take a look at below code which uses your classes but is placed inside some other package and ask yourself "how should this code behave?".
package my.pckage;
import your.pckage.A;
import your.pckage.C;
public class Test{
public static void main (String[] args){
C C = new C();
c.getNum();// ERROR: Test class doesn't have access to `c`s protected method.
// Why should it have, Test doesn't extend C.
A a = (A)c;// Lets try using other reference
a.getNum();// Should `a` have access to method that is protected in `C`?
// If yes, then what is the point of declaring this method
// protected if all I would have to do to get access to it is
// casting instance of C to A interface?
}
}
Fix the typos and try again ;)
public interface A {
public void getNum();
}
public class B {
protected void getNum() {
System.out.println("4");
}
}
public class C extends B implements A {
public void getNum() {
System.out.println("3");
}
}
First of all scope should be from lower to higher while you are overriding method in Java. scope of subclass method should be high then super class for e.g
Valid Overriding
class B {
protected void getNum() {
System.out.println("4");
}
class C extends B {
public void getNum() {
System.out.println("3");
}
InValid Overriding
class B {
public void getNum() {
System.out.println("4");
}
class C extends B {
protected void getNum() {
System.out.println("3");
}
Your second problem is you have created two public class which is not valid you can create only one public class in your java file.
When you implement an interface you need to compulsorily override it to provide concrete implementation of function(unless the class implementing the interface is abstract). In your case you are implementing an interface which make you implement getNum() function and due to overriding class you have another function with same signature which is not allowed. So you get compilation error.
Possible solution : You can make B as an interface.
The explanation by Pshemo is perfectly right that you can not reduce visibility of overridden or the interface functions.
Lets take an exapmle
class B
{
protected void getProtected1()
{
System.out.println("4");
}
protected void getProtected2()
{
System.out.println("4");
}
public void getPublic1()
{
System.out.println("4");
}
public void getPublic2()
{
System.out.println("4");
}
}
class C extends B
{
#Override
private void getPublic1() //COMPILATION ERROR : Cannot reduce the visibility of the inherited method from myzeromqApp.B
{
System.out.println("3");
}
#Override
protected void getPublic2() //COMPILATION ERROR :Cannot reduce the visibility of the inherited method from myzeromqApp.B
{
System.out.println("3");
}
#Override
private void getProtected1() //COMPILATION ERROR : Cannot reduce the visibility of the inherited method from myzeromqApp.B
{
System.out.println("3");
}
#Override
public void getProtected2() // NO ERROR IT MEANS YOU ARE ALLOWED TO INCREASE THE VISIBILITY
{
System.out.println("3");
}
}
From the above example it is clear that you are not allowed to decrease the visibility of function in any case.
In your question you are trying to implement the interface function and we know interface in Java has rules that,
Method: only public & abstract are permitted
Field: (Variables) only public, static & final are permitted
As thumb of rule, you can never decrease the visibility, of overridden or implemented methods or variables and for interface it is always public (if visibility is concerned) so those should always be public in implemented classes.
As stated, only one public class can be used per file. So, to have them all public, one must create three separate .java files. I will write the code up below, as well as detailing how to override the method to use the correct version of it in each case.
One may always have methods with the same name, but for overriding, they must have different argument lists. This is one of the compiler errors, you have three methods with the same argument lists, namely none. You may create and call the method with the correct argument list to achieve the desired result.
A.java:
package stackOverflow.tests; // Sample package for visibility
public Interface A {
public void getNum(int a); // Method takes a single integer argument
}
B.java:
package stackOverflow.tests;
public class B {
protected void getNum(int a, int b) { // Method takes two integer arguments, differing in the argument list but equal in name
System.out.println("4");
}
}
C.java:
package stackOverflow.tests;
import stackOverflow.tests.A; // Importing both classes to use their methods
import stackOverflow.tests.B;
public class C extends B implements A {
public void getNum(int a, String x) { // Takes an integer and a string argument
System.out.println("3");
}
public void getNum(int a) {
//Do nothing, as in A.java, this code is necessary to be able to override the method.
}
public static void main(String[] arguments) { // Sample main method for implementation
C c = new C(); // Instantiating class C
int test = 0; // Initializing two integer variables and one String variable
int test2 = 0;
String test3 = "";
c.getNum(test); // takes one integer, using getNum() from A.java
c.getNum(test, test2); // takes two integers, using getNum() from B.java
c.getNum(test, test3); // takes an integer and a String, using getNum() from C.java
}
}
Output:
4
3
As seen in the code above, the argument lists define which version of the method is used. As a side tip, the definition getNum(int a) is no different from getNum(int b), so this would result in it not compiling.
In order to get this working you can do something like this since there can be only one public class per file and the file name should be the same name as that of the class
public class HelloWorld{
public static void main(String []args){
C obj=new C();
obj.getNum();
}
}
//interface
interface A {
public void getNum();
}
class B {
protected void getNum() {
System.out.println("4");
}
}
class C extends B implements A {
public void getNum() {
System.out.println("3");
}
}
output:
3
A java class file can have only one public class or interface.
Change the visibility of the interface and the defined class to default level or declare it in separate files.
Only public and abstract modifiers can be applied to interface methods. The class implementing the interface cannot change the visibility of the method (we cannot change it from public to protected).

Can we create an object of an interface?

interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() {
return "test";
}
});
}
}
What is the result?
A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.
What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?
What you are seeing here is an anonymous inner class:
Given the following interface:
interface Inter {
public String getString();
}
You can create something like an instance of it like so:
Inter instance = new Inter() {
#Override
public String getString() {
return "HI";
}
};
Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.
test should be the output. This is an example of an anonymous inner class.
This is a very common pattern used with the Comparator interface as an emulation of closures.
Try this too... The name of anonymous class is generated!
Inter instance = new Inter() {
public String getString() {
return "HI" + this.getClass();
}
};
The trick is not only about the anonymous inner class, this prints test cause it overrides the toString method and while System.out.println a Object it implicit call it's toString method.
We can create an object of an anonymous class, that implements the interface:
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
If you have an interface, that declares one method toString, you can first create a class, that implements this inerface, and then create an object of this class:
interface TestA {
String toString();
}
class TestB implements TestA {
#Override
public String toString() {
return "test";
}
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestB());
}
}
Or you can create an object of an anonymous class to simplify this code:
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
#Override
public String toString() {
return "test";
}
});
}
}
In both cases it prints "test".
I don't know the significance of this question. If this is an interview question, then I can say it's okay. But in real time it's not the right approach to implement an inheritance.So coming to the answer of the question, here what you are doing is an anonymous inner class .
Here you are instantiating a class and implementing the inheritance by writing,
System.out.println(new TestA() {
public String toString() {
return “test”;
}
});
and ofcourse the result would be test

Categories