If class A creates an instance of class B, then in class B can I run a method from class A? sorry if the question is poorly worded, I don't know how else I could say it.
In the below code, Class A creates an instance of Class B and you can call Class A's method from Class B's method.
class A {
public void getA() {
System.out.println("In A");
}
public static void main(String[] args) {
B b = new B();
b.getB();
}
}
class B {
public void getB() {
System.out.println("In B");
A a = new A();
a.getA();
}
}
Output:
In B
In A
In class B you can call methods of class A only if A's methods are visible to B. It doesn't matter who created an instance of B.
This tutorial might help: http://www.tutorialspoint.com/java/java_access_modifiers.htm
So you can call it if the method is one of the following:
public
protected (and B is a subclass of A or B is in the same package as A)
no modifier (and B is in the same package as A)
Related
If there are two classes in a java program and we have another java program how can we use the function of 2nd class of first java program to 2nd java program e.g
One java program
Public class A
{
Public class B
{
void a();
void b();
}
}
Second java program
Public class C
{
i want to call void a() and void b() here
}
You can do it by inheritance.
public class C extends B {
public static void main(String args[]){
C foo = new C();
foo.a();
foo.b();
}
}
In C, you would need to create an instance of B. Let's call this instance bTest. You could then call these methods like this:
B bTest = new B();
bTest.a();
bTest.b();
Now, if you made a() and b() static methods, you would call them using the name of the class they are in rather than using an instance of it, as such:
B.a();
B.b();
Keep in mind that you will have to import B if it is not in the same package as C.
Since your inner class is not static one you have to create an object of A first and then create object of B.
A a = new A();
A.B b = a.new B();
b.a();
b.b();
I have a little confusion in Java overriding. Suppose we have the following inheritance:
class A{
public A(){
}
void show(){
System.out.println("SuperClass");
}
}
class B extends A{
#Override
void show(){
System.out.println("SubClass");
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
b.show();
}
}
Clearly, class B overrides the method show() that is inherited by the class A. Why is not b.show(); printing the message System.out.println("SuperClass"); as well since class B has now the method show() from class A?
Thank you.
The show method of class B overrides the show method of class A and doesn't call it, so there's no reason for System.out.println("SuperClass"); to be executed when you call show on an instance of B.
If you change class B to :
class B extends A
{
#Override
void show(){
super.show ();
System.out.println("SubClass");
}
}
calling show on an instance of B will also execute the logic of A's show method.
In class B you are overriding, in other words replacing the original implementation of the show() method. Every time you invoke show() on an object that is instanceof B that version of the method will be called.
The only way to refer to the original show() method is to refer to it using the super.show() syntax inside B or any other class that extends A.
And as an additional note, that #Override annotation is just to add additional compiler checks but it's not required to actually override a method, you just need to re-implement it as you have done in B.
its the matter of polymorphism which acts , i.e., method call to method body happens at run time i.e when JVM invokes B b=new B(); so B object is of type class B ,so the method it displays B's method which is overridden one, if you put super() in B()'s constructor you can get parents one.
This is the effect of overriding in inheritance. You just replace the method from the superclass (but you can still reach the old one!) Here I also added a little bit with polymorphism too. Hope that this will help you.
class A{
public A(){
}
void show(){
System.out.println("SuperClass");
}
}
class B extends A{
void superclass() {
super.show();
}
#Override
void show(){
System.out.println("SubClass");
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
b.show(); //SubClass
b.superclass(); //SuperClass
A a = new A();
a.show(); //SuperClass
A c = new B();
c.show(); //SubClass
//c.superclass(); //error! the program won't compile
}
}
In this program
class a
{
int a=25;
public void aa()
{
System.out.println(a);
}
}
class b extends a
{
int a=2;
public static void main(String[] args) {
b x=new b();
x.aa();
}
}
why does "x.aa()" prints 25 ans why not 2?,what is the reason behind it?
class a
{
int a=25;
public void aa()
{
System.out.println(a);
b();
}
public void b()
{
System.out.println("this should print");
}
}
class b extends a
{
int a=2;
public static void main(String[] args) {
b x=new b();
x.aa();
}
public void b()
{
System.out.println("this should not print");
}
}
and if we consider the above output,then here again the output of b() of above should print "this should print" but we are getting the ouput from sublcass "this should not print"
Class b inherits class A, so when you call x.aa, it is calling method aa of class a. The member a of class a is initialized with 25 so it prints 25. Class a does not know about the member a of class b.
Fields cannot be overridden, and are not virtual. B.a* is independent of A.a, to the point that they can actually have different types. There is no way for B to make A aware of B.a in place of A.a. Instances of B will actually have two fields named a, but one is hidden ("shadowed") by the other. (If desired, code B can refer to its A.a field by writing ((A)this).a. This is because the appropriate a is selected based on the type of ((A)this), which is A, rather than the runtime type of the instance, which would be B or a subtype of B.)
* Note: I have renamed your classes to A and B: per the Java naming conventions, class-names begin with uppercase letters.
b x=new b();
while you will do this this will print out put of the constructor as its giving because its clearly making the object of b class and while in the case of class A in that class that b() act as the method so it wont call when you are making object of class b.
while in the case of
b x=new b();
x.aa();
this it will by default call the inheritance and will print as u getting output.
and one more thing.
public void aa()
{
System.out.println(a);
}
in the case of this it will use the local variable of that particular class so it will print whatever you have defined on that class. in your case that is a=25;
by the way nice question.
method aa() is member of class a. so, method aa() can see/access instance member of class a.
Now, you have inherited class a to b. it means object of class b can access/call aa(). but, it doesn't mean that aa() is allowed to access variable a of class b. thats why method aa() is printing the variable a of it's own class and prints 25.
now about your second program. in class b, you are overriding method b(). while calling an overridden method, the selection of method(whether from sub class or super class) is done on the basis of instance of a invoking object(whether sub class or super class respectively).
you have called method aa() with the instance of class b that is why method b() of class b is called.
I have a function in Class A which I would like to change the value of a field in Class B.
Class C has my main() and creates a new instance of class B and Class A. Class A is from an API and one of their functions is a listener function. I would like for that listener function to be able to change the field of Class B, but when I write the code for the listener function, it doesn't recognize Class B's instance.
How do I reference that instance?
Example code:
public class A {
public void listenermethod(){
//can't reference Binstance <-------
}
}
public class B {
B.field = 1;
}
public class C {
A Ainstance = new A();
B Binstance = new B();
}
You should give A class a private B field, and then you can call the public methods from B on this field as needed. If you need to create both A and B instances in a separate class (C) you should give your A class a public void setB(B b) setter method.
A.java
class A {
private B b;
public void setB(B b) {
this.b = b;
}
public void listenerMethod() {
if (b != null) {
b.someBMethod();
}
}
}
C.java
public class C {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.setB(b);
a.listenerMethod();
}
}
You have to be able to modify both class C and class A. Rewrite the class A method to
public void listenermethod(Binstance theB){
theB.something = "some_value";
}
Now when you call class A, pass in the Binstance. If you can't modify class A, then your task can't be done.
An instance by definition belongs to an object. Therefore, your class A must either have an object of class B as a member:
Class A{
private B instance_of_b;
}
now you can access B members like this:
instance_of_b.member
or the field belonging to class B could be static and then A could access it through the class.
B.member
Also make sure you know the meaning of accessor keywords (private,protected,[friendly],public).
Consider the following code classes.
public class A
{
public A()
{
callCreation();
}
protected void callCreation()
{
System.out.println("A Created!!");
}
}
public class B extends A
{
protected void callCreation()
{
System.out.println("B Created!!");
}
}
public class C extends B
{
protected void callCreation()
{
System.out.println("C Created!!");
}
public static void main(String[] args)
{
A a = new A();
A b = new B();
A c = new C();
}
}
The output of running the class C is given below.
A Created!!
B Created!!
C Created!!
The first output line in the output A Created!! is printed because when the constructor of class A is called, it calls the super class's constructor (java.lang.Object) implicitly before calling the callCreation() method in the class A's constructor. And this will be the case for B and C classes too. In that case when the constructor of B is called the call flow should be typically : B's constructor -> A's Constructor -> java.lang.Object's Constructor -> come back to A's callCreation() method to finish calling A's constructor. If so how is the overridden value printed and not the super class's value is printed? So the question is 'when is an object of a class created exactly? to put it in other words, the object of a class should be created only after the constructor finishes calling/initializing all the elements within itself. If so how can a method be called from a child class and not from the parent class?
The callCreation methods in B and C override the method from A. So when the method is called in the constructor A the implementations in B and C will be run, even though the constructors of B and C have not been executed yet. This is possible because constructors don't actually create the object, rather they are called to initialize some moments after the JVM has created it.
In general it's a very bad idea to call methods that can be overridden from a constructor for this very reason. A method in B or C may assume that the constructor and object initializers have already been run, and read an unexpected value from a field. For example the following ends up printing "B Created!! null" because the field still has not be assigned its value.
public class B extends A
{
final String msg = "Yes!";
protected void callCreation()
{
System.out.println("B Created!! "+msg);
}
}
thinking in this way makes it more obvious:
when an object of type B is being created super() keyword calls the A constructor,
then in A constructor "this.callCreation()" is executed, which refers to the current
object which is B, so callCreation corresponding to the current object(B) is called.
the same process is done for C.
public class A {
public A() {
this.callCreation();
}
protected void callCreation() {
System.out.println("A Created!!");
}
}
class B extends A {
public B() {
super();
}
protected void callCreation() {
System.out.println("B Created!!");
}
}
class C extends B {
public C() {
super();
}
protected void callCreation() {
System.out.println("C Created!!");
}
public static void main(String[] args) {
A a = new A();
A b = new B();
A c = new C();
}
}