This code has a compilation problem. How do I get a.f()?
class A {
int i = 1;
int f() {
return i;
}
static char g() {
return 'A';
}
}
class B extends A {
int i = 2;
int f() {
return -i;
}
static char g() {
return 'B';
}
}
class Test {
public static void main(String args[]) {
B b = new B();
System.out.println(b.i);
System.out.println(b.f());
System.out.println(b.g());
System.out.println(B.g());
A a = b;
System.out.println(a.i);
System.out.println(a.f());
System.out.println(a.g());
System.out.println(A.g());
}
}
and this is the result
2
-2
B
B
1
-2
A
A
You've not specified any access modifiers for your class members, so it has default or package level access only and is not available to sub classes
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
See here for more details
If you change the signature of f() to protected int f() then it should work
Of course you have the same issue with the other members of the class so it's up to you how you control this
Overriding is just for instance methods, not for variables. So, when you get the variable i from instance of the class A, you get the value from this Class. The same thing with the instance of class B.
But you can reinitialize the value of i in constructor, for example:
class B extends A {
public B() {
i=2;
}
int f() {
return -i;
}
static char g() {
return 'B';
}
Related
So this is basically my code
abstract class B
{
int x = 3;
B()
{
x+=2;
System.out.print("-x" + x + "\n"); // print -x5
x++; // 5 then 6
}
abstract int calculate();
abstract int calculate(int i);
}
class A extends B
{
int x = 2;
A()
{
System.out.print("-x" + calculate(2)+"\n");
}
#Override
int calculate()
{
return x;
}
#Override
int calculate(int i)
{
return(calculate()+i);
}
}
public class Test2 extends A
{
Test2()
{
x+=3;
}
#Override
int calculate()
{
return x + 6;
}
public static void main(String[] args) {
Test2 sub = new Test2();
System.out.print("-x" + sub.calculate()+"\n");
}
}
My problem here is after digging up about variable hiding I learned that if a instance variable is of the same name in both parent class and child class then the childclass hides the instance variable of the parent class. Also I have the prior knowledge that variables cannot be overridden when child class inherits parent class.
So now coming to the problem, in the code when A extends to B, why does the print statement inside constructor A() gives a value -x10? shouldn't it be -x8?? I dont understand how the variable is being changed here. I am new to java so any kind of knowledge will be greatly appreciated. :)
Ok so I have done some debugging and found that the calculate(void) method in class A returns 8. But how is that possible shouldn't it return 6? Please help!
The reason it prints -x10 is because A::calculate(2) calls the Test2::calculate(), which uses A::x to do the calculation.
The sequence of calls that happens is the following:
Test2() {
A()
B() {
B::x = 3
B::x += 2
System.out.print("-x" + x + "\n"); // print -x5
B::x++ // B::x is now 6
}
A::x = 2
System.out.print("-x" + calculate(2)+"\n")
A::calculate(2) {
return(calculate()+2);
Test2::calculate() {
return A::x + 6; // A::x is 2 here, so returns 8
}
} // returns calculate()+2, so returns 10
}
A::x += 3
}
I hope this is just code to test things out, because you should never allow this to happen in real code. You should never allow a method of a subclass to be called from the constructor of a base class, because the subclass is not initialised at that time. The Java compiler does its best to prevent that, but sometimes it does not detect it.
It is returning 8 because:
The line you called System.out.print("-x" + sub.calculate()+"\n"); in class A calls
#Override
int calculate()
{
return x + 6;
}
in class A still, which is incrementing the instance variable int x = 2 in class A . this variable overwrote the one in class B
Hence 2+6 = 8
class A {
int a, b;
A(int i, int j) {
a = i;
b = j;
}
}
class B extends A {
int c, d;
B(int i, int j) {
c = i;
d = j;
}
}
public class HelloWorld {
public static void main(String[] args) {
A aa = new A(5, 6);
B bb = new B(3, 4);
System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);
}
}
it gives error as
HelloWorld.java:9: error: constructor A in class A cannot be applied to given types;
{
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
As you class B extends class A, you somewhere have to call the constructor of the class you are extending.
As your class A does not have a constructor with no arguments, you need to explicitly call the super constructor (the constructor from class A) as the first statement inside the constructor of your class B:
B(int i, int j) {
super(i, j);
// Your code
}
If you would have a no-args constructor in A, you would not need to do this, as the no-args constructor is implicitly called if no constructor call is specified:
B(int i, int j) {
// Your code
}
Is actually doing:
B() {
super();
// Your code
}
And as you do not have A() as a constructor, you get the error.
Check this one...
JVM always looking for no argument constructor.
class A {
int a, b;
A(int i, int j) {
a = i;
b = j;
}
public A() {
// TODO Auto-generated constructor stub
}
}
class B extends A {
int c, d;
B(int i, int j) {
c = i;
d = j;
}
}
public class pivot {
public static void main(String[] args) {
A aa = new A(5, 6);
B bb = new B(3, 4);
System.out.println(aa.a + aa.b + bb.a + bb.b + bb.c + bb.d);
}
}
This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 5 years ago.
I'm learning inheritance in java. While writing small code where I'm learning we cannot access private members of superclass in subclass.
Here is my code:
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
class B extends A {
int b;
void sum() {
b = i + j;
}
}
When I create a new class in eclipse, am not able to create an object of sublcass B in class A.
class mainclass{
public static void main(String args[]){
B object = new B(); ----error
}
}
}
Error says class B needs to be created.
May I know why is happening ..? Its happening not a problem but I want to solve and understand the logic why it was happened.
Thanks
That's because class B is present inside class A, it needs to be created outside of A, e.g.:
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
}
class B extends A {
int b;
void sum() {
b = i + j;
}
}
With this code, class B (and A) will be accessible from all the classes from inside the package. If you want these classes to be accessible from outside the current package then you need to create these classes in separate files and mark them as public.
Here's more on access modifiers for classes.
Upate
If you want to define class B as an inner class in A then you will need the instance of enclosing class (A in our case) to access B, e.g.:
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
class B extends A {
int b;
void sum() {
b = i + j;
}
}
}
Now, to instantiate B, you need to do the following:
A a = new A();
B b = a.new B();
And of course, same rules as access modifier will apply to inner class instance (except the fact that inner class will be able to access private members of enclosing class),
This is because an instance of class B must relate to an instance of class A. So you must first create an instance of class A, then the instance of class B:
A a = new A();
a.setij(1,2);
B b = a.new B();
b.setij(3,4);
b.sum();
System.out.println(b.b);
(the result is 5 in case you were wondering)
I'm trying to solve a problem about method calls in Java that seems really strange, I hope someone can help about it.
Here it is the code of the three classes, A is the top class with C inheriting from A and D inheriting from C.
class A {
int f(double x) {
return 1;
}
int f(boolean x) {
return 2;
}
}
class C extends A {
int f(double x) {
return 3;
}
int f(int x) {
return 4;
}
}
class D extends C {
int f(double x) {
return 5;
}
int f(int x) {
return 6;
}
}
public class test {
public static void main(String[] args) {
C b = new D();
A d = new D();
System.out.println(b.f(33));
System.out.println(d.f(33));
}
}
When I call method of object b with an int I get 6, which means that the method f(int x) from class D is called. But when I call the same method on object d I get 5, which means that the method f(double x) from class D is called. Why does it behave like that? Why an integer is considered an integer in one case and a double in the other? It is something related to how I declared the two objects but I can't get it.
The difference is in the type of the objects. b's reference is of type C and d's reference is of type A. In cases of inheritance, the JVM binds the methods at run-time, meaning that you can only call methods of the reference type, but the overridden method is the one that will run.
When you call the function on d, the JVM automatically casts to a double because A has no corresponding method for an int argument. Then, the method trickles down to D because the object is an instance of D, but it still trickles down as a double.
I was trying to make a program that searches for a random number, but i had problems importing the "a" variable in the other method. I would be happy if i could get some explanation. I have already tried to make the variable static, but that doesn't work
import java.util.Random;
public class verschlüsselung {
private static void nummber(int a) {
Random r = new Random();
a = r.nextInt(999);
System.out.println(a);
}
private static void search(int b) {
b = 0;
if(b =! a) {
for(b = 1; b =! a ; b++) {
if(b == a) {
System.out.println("found the number " + b);
}
}
}
}
public static void main(String args[]){
nummber(0);
search(0);
}
}
There is no such thing as using local variables in other methods.
You can return the variable from one method. Than call this method from other and get there the variable.
Declare the variable 'a' to be static and remove the parameter 'a' passed in the nummber()
function. This function does not need any input as it assigns the value of a random number to the global static variable 'a' which is accessed in the method search().
your declaration and method signature should read :
private static int a;
private static void nummber(){....}
May this help you:
private static int nummber( int a){
Random r = new Random();
a =r.nextInt(999);
System.out.println(a);
return a;
}
private static void search(int b, int a){
b = 0;
if(b =! a){
for(b =1; b =! a ; b++){
if(b == a){
System.out.println("found the number " + b);
}
}
}
}
public static void main(String args[]){
int a = nummber(0);
search(0, a);
}