This question already has answers here:
Different behavior of overriding methods and fields
(2 answers)
Closed 8 years ago.
Say i have this code
public class A {
String name = "a";
public void one(){
System.out.println(name);
}
public void two(){
System.out.println(name);
}
public static void main(String[] args){
A a = new A();
B b = new B();
b.one();
}
}
class B extends A{
String name="b";
public void two(){
System.out.println(name);
}
}
I cant figure out why b.one() always produces "a". From what i know of inheritance, B will see that it doesnt have its own copy of one() so it will super.one(). super.one() will print out the value of the variable name(a) in that class. However wont B see that it too has a name variable which has value "b" so wont it go to that? Im confused cause i know this logic works for method calls. Can anyone clarify this?
Your own question partially answers itself. The moment you do super.one() you are no longer in 'B'. Thus, why would you expect anything else but "a" from the name. The name that you are referencing after you call the super class is the name of A. You could change the value of name in the subclass if name was public or protected and you did not re-declare it.
public class A
{
protected String name;
public void printName()
{
System.out.println(name);
}
}
public class B extends A
{
public B()
{
name = "b";
}
}
public class Main
{
public static void main(String [] args)
{
B b = new B();
b.printName();
}
}
The above code will print "B".
Related
This question already has answers here:
Java order of Initialization and Instantiation
(2 answers)
What's wrong with overridable method calls in constructors?
(8 answers)
Closed 2 years ago.
class Main {
public static void main(String[] args) {
new B();
}
public static class A {
String f1 = "300";
public A(){
init();
}
protected void init(){}
}
public static class B extends A {
private String f1 = "3";
public B(){
super();
init();
}
protected void init(){
System.out.println(f1);
}
}
}
Output:
null
3
Can anyone explain to me the first line of the output? If I delete the line String f1 = "300";, it still has the same output also.
I have tried that if I declare some variables in B and invoke it in init() and all of it will be null in the constructor of A. In other words, my question is I want to know the reason for those variables being null at that point.
This question already has answers here:
Are static variables inherited
(4 answers)
Closed 4 years ago.
I have a code in which I expect the output to be different from the actual output.. As static variables are reference based, I expect the output to be "superclass" but what I am getting is "subclass".. Code:
class TestClass {
public static void main(String args[] ) throws Exception {
A b = new B(); // Since the reference is A, "superclass" should be the output
b.test();
}
}
abstract class A{
static String a = "superclass";
abstract void test();
}
class B extends A{
static String a = "subclass";
void test(){
System.out.println(a); // Output subclass
}
}
Please tell me where am I wrong..
Static variables are not inherited in java. You varibale static String a is static which associates it to a class. Java inheritance doesn't work with static variables.
If you absolutely want the superclass variable you could use:
System.out.println(super.a);
Here is the inheritance what you probably wish to see:
abstract class A {
String a = "superclass";
abstract void test();
}
class B extends A {
void test() {
System.out.println(a); // Output superclass
}
}
I remove the static identifier and removed the subclass's implementation of variable a. If you run this you'll get superclass as output.
A b = new B();
First off, static variables are not inherited in Java. This means that when you create your object as a new B(), even though that class extends class A, it won't keep the definition of your String a.
static String a = "subclass";
Secondly, even if that were the case, you're immediately overriding the value of String a at the beginning of this class B. You specifically set it to be "subclass" just before printing its value, so of course you've overriden the original value with this new one.
Finally, it would be a wonderful idea to try and name things with a little more variety. There being a class A and a String a doesn't help much for readability, for you or the people answering your question.
public abstract class A
{ static int a = 1; }
public class B extends A
{ static int a = 2; public A() { } }
public static void main(String argv[])
{
A var1 = new B();
System.out.println(var1.a)
// Re-cast the variable to type "class B"
// This is the SAME VARIABLE
// It is occupying the SAME MEMORY SPACE
// This println will produce the same output...
System.out.println(((B) var1).a)
}
This question already has answers here:
Call a Class From another class [closed]
(5 answers)
Closed 5 years ago.
Actually am new to Java,How to call one class1 from another class2?
Class1 has main() and other methods.Class2 has different methods.
I want to call class1 from Class2. Please provide the syntax.
You need to first create an object of type class2 and call the methods of it from main method of class1.
class2 c = new class2();
c.methodOfClass2();
Say you have the following classes:
public class A {
int a1 = 15;
public void showMessage() {
System.out.println("Hey!");
}
}
public class B {
}
In case you want your class B to be able to read a1 and call showMessage(), you need to create an object of the class they belong, in the class you'll be working in. Like this:
public class A {
int a1 = 15;
public void showMessage() {
System.out.println("Hey!");
}
}
public class B {
public static void main(String[] args) {
A a = new A();
//call either variables or methods by putting
//a. in front of them
}
}
To call methods of Class1 from Class2
If static method, call by className. e.g - Class1.staticMethodToBeCalledFromClass2();
If non-static method, you need to create object of Class1. e.g - Class1 cls1 = new Class1(); cls1.nonStaticMethodToBeCalledFromClass2();
Assuming Your code :
public class Class1{
public static void main(String[] args) {
}
public void nonStaticMethodTobeCalledFromClass2() {
}
public static void staticMethodTobeCalledFromClass2() {
}
}
public class Class2 {
public void callClass1Here() {
Class1 cls1 = new Class1();
cls1.nonStaticMethodTobeCalledFromClass2();
Class1.staticMethodTobeCalledFromClass2();
}
}
If you look at the code, you will see, to call
This question already has answers here:
Can java call parent overridden method in other objects but not subtype?
(4 answers)
Closed 8 years ago.
Is there a way to call test() in class a from class b object created in class c ?
class a {
void test(){
System.out.println("in a");
}
}
class b extends a {
void test(){
System.out.println("in b");
}
}
public class c{
public static void main(String[] args) {
b refb = new b();
refb.test();
}
}
You can do that only within the test() method of class b like following.
class b extends a {
void test(){
super.test();
System.out.println("in b");
}
}
In Java, all non static private methods are virtual by default. So, there's no way to invoke a#test from b instance unless you modify b#test. The only way to do it (by your current design) is using an instance of a:
public class c{
public static void main(String[] args) {
b refb = new b();
// code to call test() in class a
//this is the only way you have in Java
a refA = new a();
a.test();
}
}
I'm new to Java, and I've read over some tutorials on overriding methods, but an example I'm looking at isn't working the way I expect. For example, I have the code:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
#Override
public void show(){
System.out.println("B");
}
}
When I instantiate and call B.run(), I would expect to see "B" outputted. However, I see "A" instead. What am I doing wrong?
Edit: Yes, the classes are in two separate files. They're shown together for brevity.
Edit: I'm not sure how B is being instantiated, as it's being done by a third-party program using a classloader.
Edit: More info on the third-party program. It starts by calling A.main(), which I didn't initially show (sorry). I'm assuming I need to make "new A().run();" more generic to use the name of the current class. Is that possible?
That code will output B if you:
(new B()).run();
Whatever the problem is, it's not in the code you've quoted.
Updated (after your edit)
If the third-party program is calling A.main(), there's nothing (reasonable) you can do in B that will inject itself into A. As long as A.main is doing new A().run(), it's going to have an instance of A, not an instance of B. There's no "current class name" to use, or if there is (depends on your point of view), it's A, not B.
You'll have to get the third-party program to call B in some way, rather than A, or just modify A directly (e.g., getting rid of B entirely). You do not want to modify A to make it use B; that tightly binds it to a descendant and makes the separation between them largely pointless.
Hope that helps.
I tried, putting your two classes in two files, and it worked nicely, outputting "B". I called :
B b = new B();
b.run();
UPDATED : Also works as (because it is the same runtime instance):
A a = new B();
a.run();
Works for me.
Here's my code for A and B:
package so;
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
}
class B extends A{
#Override
public void show(){
System.out.println("B");
}
}
Here's my entry point:
package so;
public class EntryPoint {
public static void main(String[] args) {
B b = new B();
b.run();
}
}
It prints out 'B'.
It depends of instantiating. Try this:
A v1 = new A();
A v2 = new B();
B v3 = new A();
B v4 = new B();
v1.run()
v2.run()
v3.run()
v4.run()
I tried your example and my output was B.
How are you instantiating? Here's the exact code I ran.
public class Test {
public static class A {
public void show() {
System.out.println("A");
}
public void run() {
show();
}
}
public static class B extends A {
#Override
public void show() {
System.out.println("B");
}
}
public static void main(String args[]) {
A a = new B();
a.run();
}
}
If your external program instantiates A, you will have A, not B.
But you can try something like this, using some reflection, and pass "com.mypackage.A" or "com.mypackage.B" as arguments to your program.
With this code (exception catch missing), you will be able to print "A" or "B" depending on the string parameter that you pass.
public static void main( String[] arg ) {
String className = arg[0];
Class myClass = Class.forName(className);
Constructor cons = myClass.getConstructor(new Class[0]);
A myObject = (A) cons.newInstance(new Object[0]);
myObject.show();
}