parent reference of child object ( parent obj = new child() ) [duplicate] - java

This question already has answers here:
What is polymorphism, what is it for, and how is it used?
(29 answers)
Does polymorphism apply on class attributes in Java?
(8 answers)
Closed 3 years ago.
here ex is parent refernce of the child object
if I declare int x in derived class, the output changes to 20 , 20
however, if i dont declare x in derived class , the output is 30 , 4
i am thinking if i declare x in derived class , do 2 copies of x gets created?
please help
class base
{
public base()
{
x = 20;
}
int x = 2;
public void setval()
{
x = 5;
}
}
class derived extends base
{
int y = -1;
public derived()
{
x = 30;
}
int x = 3;
public void setval()
{
x = 4;
}
}
public class Inheritance {
public static void main(String[] args) {
base ex = new derived();
System.out.println(ex.x);
ex.setval();
System.out.println(ex.x);
}
}

When you use extend (inheritance), the child needs to use super to access the parent's methods and data fields. There is no need to re-define the variable x in the child.
Consider the block of code below:
public class Derived extends Base
{
int z;
public Derived()
{
super(); // call the parent's constructor
System.out.println(" derived constructor running");
super.x = 30; // access parent's data field x
}
public void setVal()
{
System.out.println(" x value changed in derived");
super.x = 4;
}
}

Related

Using objects in a subclass java [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I want to use objects that I've declared in one class in a subclass but it gives me non-static variable cannot be referenced from static context I'm a beginner with this so what can I change to make this work
class PairofDice {
int d61;
int d62;
PairofDice d1 = new PairofDice();
PairofDice d2 = new PairofDice();
class BoxCars {
public static void main(String[] args) {
roll();
Random rand = new Random();
int BC = 0;
for (int i = 0; i < 1000; i++) {
d1.d61 = rand.nextInt(6 + 1 - 1) + 1;
d2.d62 = rand.nextInt(6 + 1 - 1) + 1;
if (d1.d61 + d2.d62 == 12) {
BC++;
}
}
}
}
}
(ignore the roll method it's a part of something else)
Your question implies a nested class, and not what one would consider a subclass. Here is a suggested structure for your code. Before creating an instance of the inner class you need to have one of the containing class which in this case is BoxCars. You can rename the classes to whatever fits your requirement.
public class BoxCars {
public static void main(String[] args) {
BoxCars bc = new BoxCars();
PairOfDice dice = bc.new PairOfDice();
int numberOfRolls = dice.roll();
System.out.printf("I rolled %d box cars%n", numberOfRolls);
}
class PairOfDice {
int d1;
int d2;
public int roll() {
int BC = 0;
// No need to create instances of dice here. Just use d1 and d2
// code here to count the dice that are box cars.
// you have already written this.
return BC;
}
}
}

Variable Hiding confusion?

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

Not able to create an object of subclass in separate class in eclipse [duplicate]

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)

Data hiding in interface java

interface My{
int x = 10;
}
class Temp implements My{
int x = 20;
public static void main(String[] s){
System.out.println(new Temp().x);
}
}
This prints the result as 20. Is there any way that I can access the x that belongs to the interface in the class?
You need to do an explicit cast to the interface type:
System.out.println(((My)new Temp()).x);
Note however that x is not bound to any instance of My. Interface fields are implicitly static and final (more of constants), meaning the above can be done using:
System.out.println(My.x);
You can always use this.
interface My {
int x = 10;
}
class Temp implements My {
int x = 20;
public static void main(String[] s) {
System.out.println(new Temp().x); // 20
System.out.println(My.x); // 10
}
}
fields of an Interface are always static.

NullPointerException when instantiating an inner class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I know Java foreach loops are only meant to read values and not assign them, but I was wondering if they can call mutator methods on object. To find out I designed an experiment. Unfortunately the experiment crashes and I'm curious as to why.
public class test {
public static void main(String[] args)
{
foo[] f = new foo[4];
/*this would be a foreach loop, once I got the program working normally*/
for(int i = 0; i < f.length; i++) {
System.out.println(f[i].get());
f[i].add();
System.out.println(f[i].get());
}
}
private class foo {
foo() {
int x = 5;
}
void add() {
x++;
}
int get() {
return x;
}
private int x;
}
}
Gives Exception in thread "main" java.lang.NullPointerException when I expected the output to be 5 6. Is it because the constructor to foo isn't being called? If so, how can it be called? Must foo be made a static class?
You have an array of null and have not initialized any of the Foo items in the array, meaning it holds nothing but nulls.
Foo[] foos = new Foo[4];
// you need to first do this! You need to fill your array with **objects**!
for (int i = 0; i < foos.length; i++) {
foos[i] = new Foo(); // ******* add this!!*******
System.out.println(foos[i].get()); // this will now work
foos[i].add();
System.out.println(foos[i].get());
}
// now you can use the array
As an aside, your x will be 0 initially because you shadow the variable in the Foo constructor.
public class Foo {
private int x;
Foo() {
// this **re-declares the x variable**
int x = 5;
}
//....
Instead you want to do:
public class Foo {
private int x;
Foo() {
x = 5;
}
//....
Aside #2: you will want to learn and use Java naming conventions. Class names should all begin with an upper-case letter and variable names with a lower-case letter. This is important if you need others (us!!) to understand your code quickly and easily.
An example of a single class. Call it Foo.java and have it hold only one class:
public class Foo {
private int x;
public Foo() {
x = 5;
// not!
// int x = 5;
}
public void increment() {
x++;
}
public void decrement() {
x--;
}
public int getX() {
return x;
}
public static void main(String[] args) {
int fooCount = 10;
Foo[] foos = new Foo[fooCount];
for (int i = 0; i < foos.length; i++) {
foos[i] = new Foo();
System.out.println(foos[i].getX());
foos[i].increment();
foos[i].increment();
System.out.println(foos[i].getX());
}
for (Foo foo : foos) {
foo.decrement();
foo.decrement();
foo.decrement();
System.out.println(foo.getX());
}
}
}

Categories

Resources