Inner class' instance not able to access Outer class' data member - java

The documentation says "An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance." This means with the instance of inner class, I can access the members of the outer class. But I am not able to do so.
public class TopLevel {
private int length;
private int breadth;
public class NonstaticNested{
private static final int var1 = 2;
public int nonStaticNestedMethod(){
System.out.println(var1);
length = 2;
breadth = 2;
return length * breadth;
}
}
public static void main(String[] args) {
TopLevel topLevel = new TopLevel();
NonstaticNested nonStaticNested = topLevel.new NonstaticNested();
// Trying to access the length variable on 'nonStaticNested' instance, but not able to do so.
}
}

I hope the comments within the main are self speaking.
public class A {
int a = 1;
public static void main(String[] args) {
B b = new B();
// Works as "a" is defined in "A"
System.out.println(b.a);
// Works as "b" is defined in "B"
System.out.println(b.b);
C c = new C();
C.D d = c.new D();
// Works as "c" is defined in "c"
System.out.println(c.c);
// Works as "d" is defined in "D"
System.out.println(d.d);
// Error here as there is no "c" defined within "D", it´s part of "C" and here´s your
// logical mistake mixing it somewhat with what inheritance provides (just my guess).
System.out.println(d.c);
}
}
class B extends A {
int b = 1;
}
class C {
int c = 1;
class D {
int d = 2;
public D() {
// Has access to "c" defined in C, but is not the owner.
c = 2;
}
}
}

Related

Calling methods on objects Java

I'm taking an introduction to java programming course at university and have an exam next week. I'm going through past exam papers am sort of stuck on this question:
Consider the following class X: class X { private boolean a; private int b; ... }
(i) Write a constructor for this class. [2 marks]
(ii) Show how to create an object of this class. [2 marks]
(iii) Add a method out, which returns b if a is true, and -b otherwise. This method must be usable for any client of
this class. [2 marks]
I've included my code below, but what i'm stuck on is in the final part to this question. How does one call a method on a new object (as we haven't been taught that in class)? Or, does the question imply that the method has to be usable with any object, not just the created object?
Sorry for my awful code and dumb question, i'm really struggling with Java.
public class X {
private boolean a;
private int b;
X(final boolean i, final int j) {
a = i;
b = j;
}
static int Out(boolean a, int b) {
if (a == true) {
return b;
}
return -b;
}
public static void main(String[] args) {;
X object1 = new X(true, 5);
System.out.println(Out(object1));
}
}
You're very close to the solution. Simply make a method like this:
public int out() {
if (a) {
return b;
} else {
return -b;
}
}
Then you can call it in your main method like this:
X object1 = new X(true, 5);
System.out.println(object1.out());
NB: remove the semicolon at the end of public static void main(String[] args) {;
I think you were meant to create a non-static method named out, which can be called by the client of the class (any place where you create a new object of type X) using the dot notation
public int out() {
if(a)
return b;
else
return -b;
}
public static void main(String[] args) {
X object1 = new X(true, 5);
int result = object1.out();
System.out.println(result);
}

How can I access variables outside class scope but inside parent class scope? [duplicate]

This question already has answers here:
Accessing outer class variable in inner class
(2 answers)
Closed 5 years ago.
I have an exam example which ask whether or not can I access the x variable containing the value 1? The solution is that I can, but I'm interested how exactly?
class A {
int x = 1; //this is what I need access to.
class B {
int x = 2;
void func(int x) {...}
}
}
class A {
int x = 1;
class B {
int x = 2;
void func(int x) {
System.out.println(A.this.x);
}
}
}
Using example:
public class Main {
public static void main(String[] args) {
A a = new A();
A.B b = a.new B();
b.func(0); // Out is 1
}
}
To access the parent instance, you use the this keyword as in ParentClassName.this
The child class must not be static
Yes you can access variable x with value 1.
Here A is your outer class and B is Non-Static inner class.
To access variable x of outer class A you could do something like this
class B {
int x = 2;
void func(int x) {
System.out.print(A.this.x +" and "+x);
}
}

How to call an Object Method in Java

I've looked all over the internet, but I can't figure out what I'm doing wrong. I'm trying my hand at using private variables from another class using get/set methods. Something's going wrong, but I can't figure it out.
public class Character
{
private int atk = 0;
private int def = 0;
private int spd = 0;
public void setStat(String stat, int n)
{
stat = stat.toLowerCase();
if(stat.equals("def") || stat.equals("defence") || stat.equals("defense"))
{
def = n;
}
if(stat.equals("atk") || stat.equals("attack"))
{
atk = n;
}
if(stat.equals("spd") || stat.equals("speed"))
{
spd = n;
}
}
public int getStat(String stat)
{
stat = stat.toLowerCase();
int n = -1;
if(stat.equals("def") || stat.equals("defence") || stat.equals("defense"))
{
n = def;
}
if(stat.equals("atk") || stat.equals("attack"))
{
n = atk;
}
if(stat.equals("spd") || stat.equals("speed"))
{
n = spd;
}
return n;
}
public Character(int a, int d, int c)
{
atk = a;
def = d;
spd = c;
}
}
This is my first class, Character which will be used as the template for the object, complete with get/set methods.
public class newCharacters
{
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
This is my second class, which constructs a character object and then tries to get a variable. Problem is, whenever I compile, it says that the object method needs an identifier. Exact quote: <identifier> expected
I can't figure out what it means, or what I'm doing wrong? I made get/set methods for each class, created the object in both classes, even constructed and called the object method within the Character class. Same problem every time. Can someone help?
public class newCharacters
{
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
This should not be in a class. This does not mean anything. A class can have bunch of instance variables and methods.
Please study the basics well ;)
Put it in a main method inside the Character class
public static void main(String [] args) {
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
public class NewCharacters
{
public static void main(String[] args) {
Character person1 = new Character(2, 4, 3);
person1.getStat("atk");
}
}
A program starts a main method like above.
Inside a class, at the top level only fields and methods may be declared (and constructors and initializer blocks, and other classes).

trying to reassign value to class instance variables

I am being beginner trying to learn java basics and here in the this program I am confused why
we can't reassign the value of class instance variable.
this is error in this program. Please guys help me out to figure it out. thanks
class AddInsideClassVar{
int a = 3;
int c;
c = a + a;
public static void main(String args[]){
System.out.println();
}
}
You may define fields within a class, but you are not allowed to put calculation statements outside of a method definition. A field declaration is of the form type; or type = value;
For example (from your code);
class AddInsideClassVar{
static int a = 3; // ok this is a declaration for a field (variable)
static int c; // ok, this is too
//c = a + a; // this is a statement and not a declaration. A field may be
// declared only once
static int d = a + a; // this will work since it is part of a declaration.
public static void main(String args[]){
System.out.println("a=" + a + ", c=" + c + ", d=" + d);
}
}
You cannot execute c = a + a in that section. If anything you'd need to do
int a = 3;
int c = a + a;
If you make these variables static then you could do
private static int a = 3;
private static int c;
static {
c = a + a;
}
You can try this (just an example of workaround):
class AddInsideClassVar{
static {
int a = 3;
int c;
c = a + a;
System.out.println(c);
}
public static void main(String args[]){
}
}
You may be mixing your statics with instance variables. Here's how I would write this to not confuse myself:
public class AddInsideClassVar{
int a;
int c;
public void doStuff() {
a = 3;
c = a + a;
}
public static void main(String args[]){
AddInsideClassVar instance = new AddInsideClassVar();
instance.doStuff();
System.out.println(c);
}
}
a and c are instance variables. They are manipulated by a non-static method which requires an instance of the class to operate on. So, I create the instance in main(), then call the function to manipulate instance variables.
Explanation : int c = a + a is a declaration whereas " c = a + a ; " ( alone ) is a statement ; You have a point, it does not make much sense ;
class MyClass {
int a = 3;
int c = a + a; // Correct
}
or
class MyClass {
int a = 3;
int c;
public void addition () {
c = a + a; // Correct
}
}
but not
class MyClass {
int a = 3;
int c;
c = a + a; // Incorrect
}
NOTE : On the other, the Scala programming language ( compiles to JVM ) allows you to do the following :
scala> class MyClass { val a:Int = 3;
var c:Int = _;
c = a + a ; // Correct
}
defined class MyClass

Java - Using the output from one class in another

I'm trying to write a program that takes the output of adding two numbers in one class together and adds it to a different number. Here is the first class:
public class Add{
public static void main(String[] args) {
int a = 5;
int b = 5;
int c = a + b;
System.out.println(c);
}
}
And the second:
public class AddExtra{
public static void main(String[] args) {
Add a = new Add();
int b = 5;
int c = a.value+b;
System.out.println(c);
}
}
How do I get this to work? Thanks.
Suggestions:
You need to give the Add class a public add(...) method,
have this method accept an int parameter,
have it add a constant int to the int passed in,
and then have it return the sum.
If you want it to add two numbers, rather than a number and a constant, then give the method two int parameters, and add them together in the method.
Then create another class,
In this other class you can create an Add instance,
call the add(myInt) method,
and print the result returned.
You could try
public class Add{
public int c; // public variable
public Add() { // This is a constructor
// It will run every time you type "new Add()"
int a = 5;
int b = 5;
c = a + b;
}
}
Then, you can do this:
public class AddExtra{
public static void main(String[] args) {
Add a = new Add(); // Here, the constructor is run
int b = 5;
int c = a.c + b; // Access "a.c" because "c" is a public variable now
System.out.println(c);
}
}
Read more about constructors here.

Categories