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"
Related
Given the following class hierarchy
package pack1;
public class A
{
private int methodOne(int i)
{
return ++i;
}
public int methodTwo(int i)
{
return methodOne(++i);
}
}
package pack2;
import pack1.A;
class B extends A
{
int methodOne(int i)
{
return methodTwo(++i);
}
}
public class MainClass
{
public static void main(String[] args)
{
System.out.println(new B().methodOne(101));
}
}
The output of the above program is 104. Class Bcreates its own version of methodOn() because methodOne() is private in Class A. However, during runtime, when inside methodTwo(), the runtime object is of type Class B. Why would java use the methodOne() in class A as oppose of class B.
This is because, despite the name, the two methods are entirely different. methodOne in class B does not override the method with the same name in class A. As you said, B can't see the private methodOne, so it can't possibly override it. So Java creates two separate methods that are not related in any way. Then A's methodTwo calls the methodOne that's defined in A. If it were public or protected, then other classes might have overridden it, resulting in the late binding we know all too well from Java. However, the methodOne that it sees has never been overridden because B didn't know to do so.
tl;dr: Internally, they're two different and unrelated methods, even though the names are the same.
At very first your code starts executing the code
public static void main(String[] args)
{
System.out.println(new B().methodOne(101)); // it invokes methodOne() of class B.
}
Above code calls methodOne() of class B. Now, MethodOne() is private so it won't override in Class B
Now definition of methodOne() in Class B
int methodOne(int i)
{
return methodTwo(++i); // calling methodTwo() from class A which is a super class of class B.
}
this code is increase the value of i by 1. So, Now i = 102. Now again the methodTwo calling the methodOne() of class B in below code.
public int methodTwo(int i) //methodTwo in class A. part of object due to public access modifier.
{
return methodOne(++i); // it increase the value of i by 1. Now i =103.
}
Now the value of i = 103. Now it calls methodOne() of class A , because methodOne() is private in Class A
private int methodOne(int i)
{
return ++i; //again this increase the value of i by 1. Now i =104.
}
increased the value of i by 1. So, variable i = 104. So, Final value of i is 104 Now.
So, The Final Output is 104.
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;
}
}
what will be the flow of execution in case of override? What i believe is , when we call a constructor/object of any class, during execution first it call parent constructor and than child. but what will happen in case of over ridding?
lets suppose:
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
Out put of this code is:
In Class b
In Class b
what i don't understand is, why it's printing "In Class be" only, it should be "In class A and, In Class b",
when i remove override method from class b. it give me desired output.
All java methods are virtual. It means the method is called with using actual type of this. So inside of constructor A() {} this is the instance of B, so that is why you've got its method call.
Calling like this printStatus() will call the method from the same class. If you call with super.printStatus() it will envoke method from the super class (class which you have extended).
When you over-ride a method you over-ride it completely. The existence of the original implementation is completely invisible to other classes (except via reflection but that's a big topic of its own and not really relevant). Only your own class can access the original method and that is by calling super.methodName().
Note that your class can call super.methodName() anywhere, not just in the overriding function, although the most usual use for it is in the overriding function if you want the super implementation to run as well as your own.
Constructors are a slightly special case as there are rules about how and why constructors are called in order to make sure that your super-class is fully initialized when you try and use it in the inheriting class.
super is always called whether you write super(); or not.
In the example printStatus() method of Class A will never be called. Since you are creating an instance of class B and there will be method overriding. You can use the following to call the Class A printStatus() method.
public B()
{
super.printStatus();
}
When you override a method, it will override the one that you expect from class A.
Should use super keyword for calling super class method.
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
Constructor public B(){ super.printStatus(); } calls Class A print method and constructor public A(){ printStatus(); } calls Class B print method since you've overridden.
But its wrong with overridable method calls in constructors.
Try with like this :
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
For better understanding the concepts of Overloading and Overriding just go through this links:
http://en.wikibooks.org/wiki/Java_Programming/Overloading_Methods_and_Constructors
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).
I have two Java classes: B, which extends another class A, as follows :
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
I would like to call the A.myMethod() from B.myMethod(). I am coming from the C++ world, and I don't know how to do this basic thing in Java.
The keyword you're looking for is super. See this guide, for instance.
Just call it using super.
public void myMethod()
{
// B stuff
super.myMethod();
// B stuff
}
Answer is as follows:
super.Mymethod();
super(); // calls base class Superclass constructor.
super(parameter list); // calls base class parameterized constructor.
super.method(); // calls base class method.
super.MyMethod() should be called inside the MyMethod() of the class B. So it should be as follows
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() {
super.MyMethod();
/* Another code */
}
}
call super.myMethod();
I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.
class A
{
public void myMethod()
{ /* ... */ }
}
class B extends A
{
public void myMethod()
{
super.myMethod(); // calling parent method
}
}
Use the super keyword.
super.baseMethod(params);
call the base methods with super keyword and pass the respective params.
class test
{
void message()
{
System.out.println("super class");
}
}
class demo extends test
{
int z;
demo(int y)
{
super.message();
z=y;
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(6);
}
}
See, here you are overriding one of the method of the base class hence if you like to call base class method from inherited class then you have to use super keyword in the same method of the inherited class.
// Using super keyword access parent class variable
class test {
int is,xs;
test(int i,int x) {
is=i;
xs=x;
System.out.println("super class:");
}
}
class demo extends test {
int z;
demo(int i,int x,int y) {
super(i,x);
z=y;
System.out.println("re:"+is);
System.out.println("re:"+xs);
System.out.println("re:"+z);
}
}
class free{
public static void main(String ar[]){
demo d=new demo(4,5,6);
}
}
If u r using these methods for initialization then use constructors of class A and pass super keyword inside the constructor of class B.
Or if you want to call a method of super class from the subclass method then you have to use super keyword inside the subclass method like :
super.myMethod();