I would like to know how the default package is defined in Java.I know how public and private access is defined but I don't know whether there is any default package access that is defined in package level access in java.
The code I tried to execute is:
class A
{
public static void value()
{
int a;
a=5;
}
public static void main()
{
value();
}
}
class B
{
public void greet()
{
System.out.println("Value of a is"+a);
}
}
The error I got is:
D:\Downloads\pro>javac A.java
A.java:17: error: cannot find symbol
System.out.println("Value of a is"+a);
^
symbol: variable a
location: class B
1 error
Since both classes belong to the same default package shouldn't class B access class A's members(a)?
I'm asking this question because when I compile java file containing two classes since no modifier is given for classes,java compiler would give package level access as the default access modifier for the classes.Since no package is defined,java compiler would use the default package but I couldn't get whether the default package is included in package level access in java.Could anyone help me.
a is a variable inside the static function value and not visible outside of that function at all. Doesn't have to do with access specifiers.
The default package is the package without a name, all classes without a package declaration at the top of the file fall into it.
It is subject to all normal rules of packages except that you can't reference classes of it from a class inside a package.
For example I have 2 java files:
public class A{
public static void foo(){System.out.println("fooCalled");}
}
and
package com.example;
public class B{
public static void main(String[] arg){
A.foo();//won't compile
}
}
Then B (or in the qualified form com.example.B) can never call the foo of A without reflection magic.
Your program has nothing to do with access specifiers, as you have declared your variable int a inside a method.
Thus it becomes just a local variable. You cannot even use it outside this method in the same class.
If we talk specifically about access specifiers then we can have default access specifier in Java which has scope up to the same package only.
package com;
class A{
int a; // this is an instance variable
static int b; //this is a class variable
}
package com;
class B{
//can use a variable here
// To use a here, we need new A().a;
// To use b here, we can do, A.b
}
package hello;
class C{
//can't use a variable here
}
Edit
Suppose we create a file with name MyProgram.java on Desktop. Below is the code of this file,
class First{
int a; // a is an instance variable
static int b; // b is a static (class) variable
void display(){
int c; // c is a local variable
}
}
class Second{
public static void mian(){
First obj = new First();
obj.a = 10; // to access instance variable we need object of the class
obj.b = 20; // class variable can also be accessed using the object
// First.a = 10; //It won't work as a is instance variable and can be accessed by object only
// First.b = 20; // We can also access static variables by class name directly without using any object
// obj.c = 30; // It won't work. As c is a local variable of method display and can be used only inside that method.
// First.c = 30; //It also won't work as c can only be used inside the method where it is declared.
}
}
So finally I got how we could access an variable in another class without creating an object provided both classes rest in the same package.Just make the variable static.
Here's the code:
import java.io.*;
class A
{
static int a=5;
public void turn()
{
System.out.println("value of a is"+a);
}
}
class B
{
public static void main(String args[])
{
int b;
b=A.a;
System.out.println("value of a is"+b);
}
}
This shows that classes residing in the same package can access each other's members provided it is static even though it is not public because default package access comes to play.
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and
the methods in an interface are by default public.
In your class B, a is not defined.
class B {
public void greet() {
System.out.println("Value of a is" + a );//cannot find `a` inside `B`
}
}
Now coming to accessibility, since your both classes are in same package B class can access public, protected and default(no access modifiers) members of other class like A. But in your case a is a local variable inside the A member method value(), so a variable cannot be accessed outside the method where it was declared.
class A {
public static void value() {
int a;//not accessible outside this method
a=5;
}
public static void main() {//FYI: this main is not valid to execute your code, missing here: `String[] args` argument
value();
//`a`, is even not accessible here, forget about class `B`
}
}
Sample code, all are in same package:
class A {
String bar;
}
class B {
public foo() {
A a = new A();//required, as `bar` is instance(non-static) member of class `A`
a.bar 'hi there';//set value
System.out.printf("a.bar = %s\n", a.bar);
}
}
EDIT
Sample code with nested class:
class A {
int foo;
class B {
void setFoo() {
foo = 45; //accessing member of class `A`
}
}
}
Working code:
<pre>
<code>
class A {
private int foo;
private B b;
A() {
foo = -1;
b = new B();
}
class B {
void setFoo(int foo) {
System.out.printf("Inside B's setFoo(), foo = %d\n", foo);
A.this.foo = foo; //accessing member of class `A`
}
}
int getFoo() {
return foo;
}
public void setFoo(int foo) {
System.out.printf("Inside A's setFoo(), foo = %d\n", foo);
b.setFoo(foo);
}
}
class Ideone{
public static void main (String[] args) {
A a = new A();
System.out.printf("main(), foo = %d\n", a.getFoo());
a.setFoo(34);
System.out.printf("main(), foo = %d\n", a.getFoo());
}
}
</code>
</pre>
Related
If I have declared an int variable called impart and declared it in class A, and then I want to call it in class B and display it there. How would I go about doing that? I have heard you can do it by using the reserved keyword 'import', can somebody show me that way?
If you make the variable Public such as
public int potato = 15; Than that can be called in any class.
Or if you want your code to be better declare a private variable then create a method to return said variable.
public class a
{
b wow = new b();
wow.getPotato();
}
public class b
{
private potato;
public b()
{
//You dont neccessarily need this as there is a default constructor
}
public int getPotato()
return potato;
}
you will need to do something like this:
public class A {
// you still have to set a value for i
private int i;
public int getI() {
return i;
}
public class B {
public static void main(String[] args) {
A a = new A();
// now you can use the value with
a.getI();
}
}
you could also set the variable public and access it directly (or make A static as well as the variable, then you can access it without instantiating A) but this is bad coding practice
You create a Object of that Class and then call the getter method for the variable.
A aclass = new A();
aclass.getImport();
If you make the variable static, you can use int b = A.impart;. Making the variable static allows you to cross it over to another class without having to get a reference to the class.
This question already has answers here:
What is the difference between local and instance variables in Java?
(13 answers)
Closed 5 years ago.
I want to know the difference between class variable and variable declared inside the constructor. For example:
class A {
int a;
}
vs
class A {
public A() {
int a;
}
}
when you do
class A {
int a;
}
the integer a can be accessed by any other instance method in the class A, and any child object (some package restrictions) of that class as well...
so the main difference is the scope of that variable
on the other hand... when you do
public A() {
int a;
}
the variable a is out of that scope as soon as the constructor returns...
In
class A {
int a;
}
the variable can be used anywhere in the class
But, in
class A {
public A() {
int a;
}
}
the variable a can only be accessed inside the function A()
So
class A {
int a;
public printA() {
Log.i("TEST", a); // will work fine
}
}
but
class A {
public printA() {
int a;
Log.i("TEST", a); // will work fine
}
public void printA1() {
...
...
Log.i("TEST", a); // will throw an error
}
}
in class A { int a; } the variable a is shared in the whole class, by all the methods you will implement in it (and to other package's classes, int that precise case).
As for class A { public A() { int a; } } the variable a is only accessible within the constructor's scope. That means it is destroyed when the constructor returns.
In the first class, a is heap-allocated, and in the other case it is stack-allocated.
Class variables are 2 types
Static variables - Class level variables
Non static variable - Instance variable
Constructors, instance methods can access both static and non static variables, but constructor variables are local variables like method variables, we can't access outside of the constructor.
class A
{
int a = 2, b = 3;
public void display()
{
int c = a + b;
System.out.println(c);
}
}
class B extends A
{
int a = 5, b = 6;
}
class Tester
{
public static void main(String arr[])
{
A x = new A();
B y = new B();
x.display();
y.display();
}
}
Why does the output come out as 5,5? And not 5,11?.How would the y.display() method work?
why does the output comes 5,5?
Because A.display() only knows about the fields A.a and A.b. Those are the only fields that any code in A knows about. It looks like you expect the declarations in B to "override" the existing field declarations. They don't. They declare new fields which hide the existing fields. Variables don't behave virtually in the way that methods do - the concept of overriding a variable simply doesn't exist. From the JLS section 8.3:
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
You can get the effect you want by changing B so that its constructor changes the values of the existing fields that it inherits from A instead:
class B extends A {
B() {
a = 5;
b = 6;
}
}
Note that these are not variable declarations. They're just assignments. Of course in most code (well, most code I've seen anyway) the fields in A would be private, so couldn't be accessed from B, but this is just example for the purpose of explaining the language behaviour.
In class A you declare fields a and b. The method display uses these fields. In class B you declare NEW fields of the same name. You're actually hiding the old fields not "overriding" them. To assign different values to the same fields use a constructor:
class A {
A(int a, int b) {
this.a = a;
this.b = b;
}
A() {
this(2, 3);
}
int a,b;
public void display() {
int c=a+b;
System.out.println(c);
}
}
class B extends A {
B() {
super(5, 6);
}
}
When doing this:
class B extends A
{
int a = 5, b = 6;
}
you are not redefining a and b, you're creating new variables with the same names. So you end up with four variables( A.a, A.b, B.a, B.b).
When you call display() and calculate the value of c, A.a and A.b will be used, not B.a and B.b
There isn's anything called variable overriding. That is why you are getting the same result in both the cases.
The reason is that Java uses the concept of lexical scope for variable resolution.
Fundamentally, there are two possible options to resolve free variables in a function ('free' means not local and not bound to function parameters):
1) against the environment in which the function is declared
2) against the environment in which the function is executed (called)
Java goes the first way, so free variables in methods are resolved [statically, during compilation] against their lexical scope (environment), which includes:
method parameters and local method variables
field declarations in the class containing method declaration
public field declarations in parent class
and so on, up the chain of inheritance
You would see this behaviour implemented in most programming languages, because it is transparent to developer and helps prevent errors with shadowing of variables.
This is opposite to the way methods work in Java:
class A {
public void foo() {
boo();
}
public void boo() {
System.out.println("A");
}
}
class B extends A {
#Override
public void boo() {
System.out.println("B");
}
}
class Main {
public static void main(String[] args) {
B b = new B();
b.foo(); // outputs "B"
}
}
This is called dynamic dispatch: method call is resolved dynamically in runtime against the actual object, on which it is called.
When you compile your code it pretty much becomes like:
class A extends java.lang.Object
{
int a=2,b=3;
public void display()
{
int c=a+b;
System.out.println(c);
}
}
class B extends A
{
int a = 5, b = 6;
public void display()
{
super(); //When you call y.display() then this statement executes.
}
}
class Tester
{
public static void main(String arr[])
{
A x = new A();
B y = new B();
x.display();
y.display();
}
}
And hence, when super calls, the method of class A is being called.
Now go to method of class A. Here int c = a + b; means
c = this.a + this.b; which is 2 + 3.
And the result is 5.
Class B declares variables in B scope, public void display() is part of A class and knows only about its own scope variables.
It's the inheritance functaionality which gives the output 5,5.
Java doesn't have anything like variable overriding. Thus, when the method display() is invoked, it accesses the variables inside the parent class 'A' and not the variables inside the subclass 'B'.
It can be explained with the same reason of why you can't print a variable declared in a subclass (and not in superclass) inside superclass method. The superclass method simply doesn't have access to the subclass variables.
However, you'll be able to print 5,11 if you have accessor methods to the fields in both the classes and you use those accessor methods to get the values instead of directly accessing using variable names. (even if the display() method is present only in superclass). This is because the overridden accessor methods are invoked (in second case) which return the values from the subclass.
Why does the output come out as 5,5? And not 5,11?
Whenever we have same instance variables (applicable to class variable as well) in a class hierarchy, the nearest declaration of the variable get the precedence. And in this case, nearest declaration of a and b from display () method is A’s. So class B’s instance variables go hidden. Hence in both cases, 5 gets printed.
How would the y.display() method work?
Another alternative is to have getter in both classes to get value of a and b.
class A
{
int a = 2, b = 3;
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display()
{
int c = getA() + getB();
System.out.println(c);
}
}
class B extends A
{
int a = 5, b = 6;
public int getA() {
return a;
}
public int getB() {
return b;
}
}
class Tester
{
public static void main(String arr[])
{
A x = new A();
B y = new B();
x.display();
y.display();
}
}
Prints
5
11
interface abs{
int a=10;// by default final static
void callme();
}
class B implements abs{
int a =11;// reinitializing
void call()
{
System.out.println("No problem"+a);
}
public void callme()
{
System.out.println("Call me"+a);
}
}
class main{
public static void main(String args[]){
B m=new B();
m.call();
m.callme();
}
}
In Herbert Schildt book, I have read that the interface variables are default Final and static. Which implicitly means that it will act like a constant. but when I am assigning 11 in the variable a in my above mentioned code, it is not giving any error.
o/p
No problem11
Call me11
You're not re-initializing the variable, but you're hiding it.
In order to access abs's a member, you have to refer it with the interface name. Something like:
System.out.println("No problem" + abs.a);
Because you have declared variable again
int a =11;
so see the error you want
do this in your class
a=11;
in your case the a is an entire new variable belonging to class B
You are not modifying the value of abs.a when you initialize a in class B. The field B.a simply hides the inherited a from the interface. You can still get to abs.a from code in class B by using the fully qualified name abs.a.
No, You can't reinitialize Interface variable. The variable in your Implementation Class is not interface variable A, but B class' instance variable. If you want to access Interface variable you reference it as abs.A
What you are actually doing is hiding the variable in interface by declaring a variable with same name in class B. You can verify it by using this code:
public interface Abs {
int a=10;// by default final static
void callme();
default void printA() {
System.out.println("A in interface: " + a);
}
}
public class B implements Abs {
int a =11;// reinitializing
void call()
{
System.out.println("A in class: "+a);
}
public void callme()
{
printA();
}
}
Then we have:
public static void main(String[] args){
B m=new B();
m.call();
m.callme();
}
It prints:
A in class: 11
A in interface: 10
public class Ex7 {
private int fld;
private void meth(int val) {
fld = val;
System.out.println(" meth() -> fld = " + fld);
}
public class Ex7Inner1 {
void operateOnFld() {
fld = 12;
}
void operateOnMeth() {
meth(10);
}
public void bar() {
System.out.println(" bar() ");
}
}
class Ex7Inner2 {
Ex7Inner1 i1 = new Ex7Inner1();
// how to call i1.bar() ??
i1.bar();
}
}
Your problem is that you need to call i1.bar() inside a function. For example
class Ex7Inner2 {
Ex7Inner1 i1 = new Ex7Inner1(); // this is now a field of the Ex7Inner2 class
public void callBar() {
i1.bar(); // this will work
}
}
In the future, you may find that people are able to be more helpful if you include the error you get in your question, which I'll do now. When you try to compile the code your way, you get an error that looks like
Ex7.java:26: <identifier> expected
i1.bar();
^
1 error
This is because the only thing you can do outside of a method (like you originally had it) is declare variables. So it was expecting an "identifier" by which it meant "the name of the variable you are declaring". So if you had said
String s;
then s would have been the identifier.
A few things wrong here;
your inner2 needs to be calling the
i1 inside of a function
since you didn't declare inner1
static it needs an instance of the
enclosing Ex7 to exist.
So you can do something like this:
public class Ex7 {
private Ex7Inner1 i1;
public class Ex7Inner1 {
public void bar() {
System.out.println( " bar() " );
}
}
class Ex7Inner2 {
// how to call i1.bar() ??
public Ex7Inner2() {
Ex7.this.i1.bar();
}
}
}
To access the Ex7's i1.
Where your Ex7 instance contains an inner1 and an inner2 and your reference from within inner2 is inner2-->parentEx7 -->child inner1.
If you make the inner class static you can do away with the Ex7 reference, as you're defining that the inner class doesn't need an instance of the outer class to exist.
but there are no method in Ex7Inner2 class.
create method with 'i1.bar();' call inside and it compiles ok
Ex7Inner1 needs a reference to Ex7 in order to instantiate. From Ex7Inner2 that reference is Ex7.this.
Thus say
Ex7Inner1 i1 = Ex7.this.new Ex7Inner1()
See the Java Tutorial from more information.