public class Foo {
public int a = 3;
public void addFive(){
a += 5; System.out.print("f ");
}
}
public class Bar extends Foo {
public int a = 8;
public void addFive(){
this.a += 5;
System.out.print("b " );
}
}
public class Test {
public static void main(String args[]){
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
I am getting output b 3 .why it is not giving b13 as output.Can anyone please explain.
Assuming class Foo is declared as below
class Foo
{
public int a = 3;
public void addFive()
{
a += 5;
System.out.print("f ");
}
}
Variables have no concept of overriding. They are just masked.
It is printing 3 because, when you use a superclass reference to access a variable, it accesses the variable declared in superclass only. Remember that superclass doesn't know anything about subclass.
class Foo {
public void addFive() {
a += 5; System.out.print("f ");
}
}
you don't have 'a' variable defined, so this example doesn't even compile.
correct code:
class Foo {
public int a;
public void addFive() {
a += 5; System.out.print("f ");
}
}
and see link https://stackoverflow.com/a/2464254/1025312
I assume that you meant to declare an integer field a in class Foo.
The answer to your question has to do with concepts of 'overriding' and 'hiding', as others have pointed out. Another way to explain it is that for member variables, there is no such thing as 'dynamic dispatch'. What that means is that, if you access a member of a certain object, the system checks at run time which member you mean, by looking at the class hierarchy.
So, when calling the method f.addFive, at run time, the system will see that your object is actually a Bar and not a Foo, and so take the addFive function that you defined in the Bar class.
That does not happen for member variables: you access f.a in your print statement, and at compile time it is decided that right there you want to access the field a declared in class Foo there -- and so, that is what will happen at run time.
Now, the reason that there is no dynamic dispatch for member variable access is performance: it would be very expensive to go through the whole 'see what object this really is' logic every time you just want to add some value to a member variable.
Declaring public int a = 8 in Foo class instead of Bar class it should work... printing B 3.
But I suppose you are talking about a question included in the Java certification exam, so you have to correct the code of the Foo class adding public int a = 3.
You cannot override a variable in Java, but declaring in as public (or protected) in the super-class you can use it also in all inherited classes.
In this case the right output is B 13 because in the test class you are using a Bar object as a Foo object, so the value of a is 3 and not 8.
Related
What I assume is that an inherited method will, by standard, use the methods and attributes of the class whose object is used to execute that method.
Here's an example for my question, it's from a task from an older exam:
public class Test {
public static void main(String[] args) {
A a = new A(3);
A b = new B(1, 4);
b.methodOne(6); // <----- This. I think that this uses "b.m" and "b.increase"
}
}
public class A {
private int m;
private int n;
public A(int n) {
m = n;
}
public void methodOne(int i) {
m -= i;
increase(i);
}
public void increase(int i) {
m += 2 * i;
}
public void visilibityTest() {
n++; // <----- I think that b.visibilityTest() would work
// Because it uses the visibility "rights" of A.
}
}
public class B extends A {
private int m;
public B(int m, int n) {
super(n);
this.m = m + 1;
}
public void increase(int i) {
m += i;
}
}
As I said in the comments, I think that by executing b.methodOne, the attribute "b.m" and the method "b.increase" are used, even though methodOne is inherited from class A. (I mean this.m of b, not super.m)
1. Is this true? Do inherited methods normally use the methods and attributes of the subclass?
2. What role do the static/dynamic type play in this task? ("A b = new B")
And what about visibility? In another task I found out that if you use inherited methods to access private attributes of the superclass (that should not be visible to a subclass), you can access those attributes, as if you were accessing superclass's visibility rights. I added an example method called visibilityTest() to show that example on this task. Would that work?
3. Do inherited methods use the visibility of the superclass?
I apologize for any unclear wording. I'm both still trying to understand most of this, and also have to find out what many terms are called like in English, for the purpose of translation.
Any pointing out of unclear wording will be appreciated.
Yes, this is correct. When a method is inherited from a superclass, the subclass can override it to change the behavior, but if not overridden, it will use the implementation in the superclass. In this case, calling b.methodOne(6) will use the m and increase from the B class, since b is an object of type B.
The static type refers to the type of a reference variable (in this case A b) whereas the dynamic type refers to the actual type of the object referred to by the reference variable (in this case B). When you call b.methodOne(6), the static type is A but the dynamic type is B. This means that the method methodOne is resolved based on the type of the object b refers to (dynamic type B) rather than the type of the reference variable b (static type A).
Inherited methods use the visibility of the superclass unless they are overridden in the subclass. In this case, b.visibilityTest() would work, because it is a method in the superclass A and visibility is not changed by inheritance.
Preface
I'd like to saying two things:
I don't know how to phrase this question in a few words. So I can't find what I'm looking for when searching (on stackoverflow). Essentially, I apologize if this is a duplicate.
I've only been programming Java consistently for a month or so. So I apologize if I asked an obvious question.
Question
I would like to have a method with a parameter that holds (path to) an integer.
How is such a method implemented in Java code?
Restrictions
The parameter should be generic.
So, when there are multiple of that integer variables, the correct one can be used as argument to the method, when it is called (at runtime).
My Idea as Pseudo-Code
Here's the idea of what I want (in pseudo-code). The idea basically consist of 3 parts:
the method with parameter
the variables holding integer values
the calls of the method with concrete values
(A) Method
.
Following is the definition of my method named hey with generic parameter named pathToAnyInteger of type genericPathToInt:
class main {
method hey(genericPathToInt pathToAnyInteger) {
System.out.println(pathToAnyInteger);
}
}
(B) Multiple Integer Variables
Following are the multiple integer variables (e.g. A and B; each holding an integer):
class A {
myInt = 2;
}
class B {
myInt = 8;
}
(C) Method-calls at runtime
Following is my main-method that gets executed when the program runs. So at runtime the (1) previously defined method hey is called using (2) each of the variables that are holding the different integer values:
class declare {
main() {
hey("hey " + A.myInt);
hey("hey " + B.myInt);
}
}
Expected output
//output
hey 2
hey 8
Personal Remark
Again, sorry if this is a duplicate, and sorry if this is a stupid question. If you need further clarification, I'd be willing to help. Any help is appreciated. And hey, if you're going to be unkind (mostly insults, but implied tone too) in your answer, don't answer, even if you have the solution. Your help isn't wanted. Thanks! :)
Java (since Java 8) contains elements of functional programing which allows for something similiar to what you are looking for. Your hey method could look like this:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
This method declares a parameter that can be "a method call that will return an Integer".
You can call this method and pass it a so called lambda expression, like this:
hey(() -> myObject.getInt());
Or, in some cases, you can use a so called method referrence like :
Hey(myObject::getInt)
In this case both would mean "call the hey method and when it needs an integer, call getInt to retrieve it". The lambda expression would also allow you to reference a field directly, but having fields exposed is considered a bad practise.
If i understood your question correctly, you need to use inheritance to achive what you are looking for.
let's start with creating a hierarchy:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
Now you method Signature can be accepting and parameter of type SuperInteger and while calling the method, you can be passing SubIntA/SuperInteger/SubIntB because Java Implicitly Upcasts for you.
so:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
can be called from main using:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
getting an Output like:
A Value is :3
B Value is :3
The Value is :3
Integers in Java are primitive types, which are passed by value. So you don't really pass the "path" to the integer, you pass the actual value. Objects, on the other hand, are passed by reference.
Your pseudo-code would work in Java with a few modifications. The code assumes all classes are in the same package, otherwise you would need to make everything public (or another access modifier depending on the use case).
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
This code first defines the class MainClass, which contains your method hey. I made the method static in order to be able to just call it as MainClass.hey(). If it was not static, you would need to instantiate a MainClass object in the Declare class and then call the method on that object. For example:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...
Okay, I'm a newbie and I need some advice about organization in my code. I've been getting an error that says my arraylist cannot resolved.
What I'm doing is I'm extending an abstract class (I don't know if thats relevant) and I've created an array list in my main and filled it with things and then I've got my method to print out the contents of that array list.
If anyone can help me, please do. Thanks
Here's my code:
public static void main(String[] args) {
ArrayList <String> Strings = new ArrayList <String>();
Strings.add("Hi");
Strings.add("How are you");
Strings.add("Huh");
}
public void showFirstString(){
for (int i = 0; i < Strings.size(); i++){
System.out.println(Strings(i));
}
}
Please avoid using the word String as a variable name because java already used it as a keyword. Just replace it with another name.
Here is what you should do because you are using ArrayList:
public static void main(String[] args) {
ArrayList <String> list= new ArrayList <String>();
list.add("Hi");
list.add("How are you");
list.add("Huh");
showFirstString(list);
}
public static void showFirstString(ArrayList list){
for (int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
And make sure to import the ArrayList library.
read more about its docu here
You need to use the .get(index) method, where index is the element you want to access. For example:
System.out.println(Strings.get(i));
You would also want to call that method in main.
You never call showFirstString() and in addition, Strings isn't a global variable, so you will get an error on the first line of that method. To fix this, put showFirstString(Strings) in your main method and change your method signature to public void showFirstString(Arraylist Strings). In addition, arraylists are accessed using list.get(index) so change the line in your loop to System.out.println(Strings.get(i));
If you want to get elements from an array list, you have to use list.get(index) method as follows. It's because you cannot access elements as in arrays when it comes to array lists.
public void showFirstString(){
for (int i = 0; i < Strings.size(); i++){
System.out.println(Strings.get(i));
}
}
First of all, your naming convention is not very good.
Second,List collection circular elements is list.get(index),is not list(index)
There are answers that address what OP should do to improve but I feel the important part in his question my arraylist cannot resolved. is not discussed. My answer adds to that part.
When compilers complain XXX cannot be resolved, it means that the compiler is encountering the variable's name for the first time and has no idea of what the stuff with that name is. In your case, the compiler does not know what is Strings in showFirstString(), and because it does not know what is Strings, it stops compiling and complains to you instead of keep going with knowing nothing about it, which could potentially be dangerous.
The reason the compiler could not know what was Strings in showFirstString() is known as the scope of variables. Basically, there are lots of blocks in Java as in:
public void myMethod()
{ /* method body block is here* }
or even like,
public class myClass
{
/* here starts the class body */
public static void myMethod()
{ /* method body block is here* }
}
And the thing is that the variables are known only within a block where it's declared. So for example, if your codes looks like this:
public class myClass
{
int foo; // it is known to everywhere within this class block
public static void myMethod()
{
// boo is known only within this method
int boo = foo + 1; // fine, it knows what foo is
}
public static void myMethod2()
{
// bar is known only within this method
int bar = boo + 1; // cause errors: it does not know what boo is
}
}
Now you should understand why your programme was not able to know what is Strings. But passing around data within your codes is a common stuff that is often required to do. To achieve this, we pass parameters to methods. A parameter is a data specified within () that follows the name of the method.
For example:
public class myClass
{
int foo; // it is known to everywhere within this class block
public static void myMethod()
{
// boo is known only within this method
int boo = foo + 1; // fine, it knows what foo is
myMethod2(boo); // value of boo is passed to myMethod2
}
public static void myMethod2(int k) // value of k will be boo
{
// bar is known only within this method
int bar = k + 1; // cause errors: it does not know what boo is
}
}
With parameters like above, you can use boo in myMethod2(). The final thing is that with the codes above, your codes will compile but will do nothing when you run it, because you did not start any of the methods. When a programme runs, it looks for the main method and any other methods that you want to invoke should be called in methods, or by other methods that are in main.
public class myClass
{
int foo; // it is known to everywhere within this class block
public static void main(String[] args)
{
// start myMethod
myMethod();
}
public static void myMethod()
{
// boo is known only within this method
int boo = foo + 1; // fine, it knows what foo is
myMethod2(boo); // value of boo is passed to myMethod2
}
public static void myMethod2(int k) // value of k will be boo
{
// bar is known only within this method
int bar = k + 1; // cause errors: it does not know what boo is
}
}
I hope you get the idea. Also note that to get the items in an ArrayList, you need to use ArrayList.get(int index), as others noted.
First of all, as others have pointed out, you will need to use the Strings.get(i) method to access the value stored inside a given list element.
Secondly, as Matthias explains, the variable Strings is out of scope and therefore cannot be accessed from the showFirstString() method.
Beyond that, the problem is that your main() method, which is static, cannot interact with the instance method showFirstString() and vice versa.
Static methods live at the class level and do not require an instance of that class to be created. For example:
String.valueOf(1);
Instance methods on the other hand, as the name implies, require an instance of that class to be created before they can be called. In other words, they are called on the object (instance of the class) rather than the class itself.
String greeting = "hi there";
greeting.toUpperCase();
This provides further details:
Java: when to use static methods
Without knowing your specific situation, you have two options...
Make both your Strings list as static (class level) field and showFirstString() method static.
public class ListPrinterApp {
static ArrayList<String> Strings = new ArrayList <String>();
public static void main(String[] args) {
Strings.add("Hi");
Strings.add("How are you");
Strings.add("Huh");
showFirstString();
}
static void showFirstString(){
for (int i = 0; i < Strings.size(); i++){
System.out.println(Strings.get(i));
}
}
}
Move code that deals with the list into a separate class, which is then called from your application's static main method. This is likely a better option.
public class ListPrinter {
ArrayList<String> Strings = new ArrayList<String>();
public ListPrinter() {
Strings.add("Hi");
Strings.add("How are you");
Strings.add("Huh");
}
public void showFirstString() {
for (int i = 0; i < Strings.size(); i++) {
System.out.println(Strings.get(i));
}
}
}
public class ListPrinterApp {
public static void main(String[] args) {
ListPrinter printer = new ListPrinter();
printer.showFirstString();
}
}
(I put the the Strings.add() calls into the constructor of ListPrinter as an example. Presumably, you would not want to hardcode those values, in which case you should add an add() method to your ListPrinter class through which you can populate the list.)
A few additional points not directly related to your question:
Take a look at the naming conventions for variables in Java. Specifically:
If the name you choose consists of only one word, spell that word in
all lowercase letters. If it consists of more than one word,
capitalize the first letter of each subsequent word.
Consider using the interface List instead of the concrete implementation of ArrayList when declaring your variable (left side of the equals sign). More info here.
My code is:
class Foo {
public int a=3;
public void addFive() {
a+=5;
System.out.print("f ");
}
}
class Bar extends Foo {
public int a=8;
public void addFive() {
this.a += 5;
System.out.print("b ");
}
}
public class TestClass {
public static void main(String[]args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
Output:
b 3
Please explain to me, why is the output for this question "b 3" and not "b 13" since the method has been overridden?
F is a reference of type Foo, and variables aren't polymorphic so f.a refers to the variable from Foo which is 3
How to verify it?
To test this you can remove a variable from Foo , it will give you compile time error
Note: Make member variable private and use accessors to access them
Also See
Why use getters and setters?
You cannot override variables in Java, hence you actually have two a variables - one in Foo and one in Bar. On the other hand addFive() method is polymorphic, thus it modifies Bar.a (Bar.addFive() is called, despite static type of f being Foo).
But in the end you access f.a and this reference is resolved during compilation using known type of f, which is Foo. And therefore Foo.a was never touched.
BTW non-final variables in Java should never be public.
With such a question, the SCJP exam is assessing your knowledge of what is known as hiding. The examiner deliberately complicated things to try to make you believe that the behavior of the program depends only on polymorphism, wich it doesn't.
Let's try to make things a bit clearer as we remove the addFive() method.
class Foo {
public int a = 3;
}
class Bar extends Foo {
public int a = 8;
}
public class TestClass {
public static void main(String[]args) {
Foo f = new Bar();
System.out.println(f.a);
}
}
Now things are a bit less confusing. The main method declares a variable of type Foo, which is assigned an object of type Bar at runtime. This is possible since Bar inherits from Foo.The program then refers to the public field a of the variable of type Foo.
The error here would be to believe that the same kind of concept known as overriding applies to class fields. But there is no such a concept for fields: the public field a of class Bar is not overriding the public field a of class Foo but it does what is called hiding. As the name implies, it means that in the scope of the class Bar, a will refer to Bar's own field which has nothing to do with Foo's one. (JLS 8.4.8 - Inheritance, Overriding, and Hiding)
So, when we are writing f.a, which a are we referring to? Recall that resolution of the field a is done at compile time using the declaring type of the object f, which is Foo. As a consequence, the program prints '3'.
Now, lets add an addFive() method in class Foo and override it in class Bar as in the exam question. Here polymorphism applies, therefore the call f.addFive() is resolved using not the compile time but the runtime type of object f, which is Bar, and thus is printed 'b '.
But there is still something we must understand: why the field a, which was incremented by 5 units, still sticks to the value '3'? Here hiding is playing around. Because this is the method of class Bar which is called, and because in class Bar, every a refers to Bar's public field a, this is actually the Bar field which is incremented.
1) Now, one subsidiary question: how could we access the Bar's public field a from the main method? We can do that with something like:
System.out.println( ((Bar)f).a );
which force the compiler to resolve the field member a of f as Bar's a field.
This would print 'b 13' in our example.
2) Yet another question: how could we work around hiding in addFive() method of class Bar to refer not to the Bar's a field but to its superclass eponimous field ? Just adding the super keyword in front of the field reference does the trick:
public void addFive() {
super.a += 5;
System.out.print("b ");
}
This would print 'b 8' in our example.
Note that the initial statement
public void addFive() {
this.a += 5;
System.out.print("b ");
}
could be refined to
public void addFive() {
a += 5;
System.out.print("b ");
}
because when the compiler is resolving the field a, it will start to look in the closest enclosing scope from within the method addFive(), and find the Bar class instance, eliminating the need to use explicitely this.
But, well, this was probably a clue for the examinee to solve this exam question !
Since you are doing f.a you will get the value of a from the class Foo. if you had called a method to get the value, e.g getA() then you would have gotten the value from the class Bar.
Consider the int a variables in these classes:
class Foo {
public int a = 3;
public void addFive() { a += 5; System.out.print("f "); }
}
class Bar extends Foo {
public int a = 8;
public void addFive() { this.a += 5; System.out.print("b " ); }
}
public class test {
public static void main(String [] args){
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
I understand that the method addFive() have been overridden in the child class, and in class test when the base class reference referring to child class is used to call the overridden method, the child class version of addFive is called.
But what about the public instance variable a? What happens when both base class and derived class have the same variable?
The output of the above program is
b 3
How does this happen?
There are actually two distinct public instance variables called a.
A Foo object has a Foo.a variable.
A Bar object has both Foo.a and Bar.a variables.
When you run this:
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
the addFive method is updating the Bar.a variable, and then reading the Foo.a variable. To read the Bar.a variable, you would need to do this:
System.out.println(((Bar) f).a);
The technical term for what is happening here is "hiding". Refer to the JLS section 8.3, and section 8.3.3.2 for an example.
Note that hiding also applies to static methods with the same signature.
However instance methods with the same signature are "overridden" not "hidden", and you cannot access the version of a method that is overridden from the outside. (Within the class that overrides a method, the overridden method can be called using super. However, that's the only situation where this is allowed. The reason that accessing overridden methods is generally forbidden is that it would break data abstraction.)
The recommended way to avoid the confusion of (accidental) hiding is to declare your instance variables as private and access them via getter and setter methods. There are lots of other good reasons for using getters and setters too.
It should also be noted that: 1) Exposing public variables (like a) is generally a bad idea, because it leads to weak abstraction, unwanted coupling, and other problems. 2) Intentionally declaring a 2nd public a variable in the child class is a truly awful idea.
From JLS
8.3.3.2 Example: Hiding of Instance Variables This example is similar to
that in the previous section, but uses
instance variables rather than static
variables. The code:
class Point {
int x = 2;
}
class Test extends Point {
double x = 4.7;
void printBoth() {
System.out.println(x + " " + super.x);
}
public static void main(String[] args) {
Test sample = new Test();
sample.printBoth();
System.out.println(sample.x + " " +
((Point)sample).x);
}
}
produces the output:
4.7 2
4.7 2
because the declaration of x in class
Test hides the definition of x in
class Point, so class Test does not
inherit the field x from its
superclass Point. It must be noted,
however, that while the field x of
class Point is not inherited by class
Test, it is nevertheless implemented
by instances of class Test. In other
words, every instance of class Test
contains two fields, one of type int
and one of type double. Both fields
bear the name x, but within the
declaration of class Test, the simple
name x always refers to the field
declared within class Test. Code in
instance methods of class Test may
refer to the instance variable x of
class Point as super.x.
Code that uses a field access
expression to access field x will
access the field named x in the class
indicated by the type of reference
expression. Thus, the expression
sample.x accesses a double value, the
instance variable declared in class
Test, because the type of the variable
sample is Test, but the expression
((Point)sample).x accesses an int
value, the instance variable declared
in class Point, because of the cast to
type Point.
In inheritance, a Base class object can refer to an instance of Derived class.
So this is how Foo f = new Bar(); works okay.
Now when f.addFive(); statement gets invoked it actually calls the 'addFive() method of the Derived class instance using the reference variable of the Base class. So ultimately the method of 'Bar' class gets invoked. But as you see the addFive() method of 'Bar' class just prints 'b ' and not the value of 'a'.
The next statement i.e. System.out.println(f.a) is the one that actually prints the value of a which ultimately gets appended to the previous output and so you see the final output as 'b 3'. Here the value of a used is that of 'Foo' class.
Hope this trick execution & coding is clear and you understood how you got the output as 'b 3'.
Here F is of type Foo and f variable is holding Bar object but java runtime gets the f.a from the class Foo.This is because in Java variable names are resolved using the reference type and not the object which it is referring.