Why I cannot access class after I use package? [duplicate] - java

This question already has answers here:
How to access java-classes in the default-package?
(5 answers)
Closed 8 years ago.
I write a normal class
public class TestAccess {
}
class T{
private int i=0;
int j=0;
protected int k=0;
public int m=0;
}
class TT
{
public void m(){
T t= new T();
t.j=9;
}
}
Then I access it in the same directory with another class
public class TestProtected extends T
{
public void method(){
System.out.println(k);
}
public static void main(String[] args)
{
System.out.println("HW!");
}
}
But when I use package in the second class, there is something wrong to access class T;
package m;
public class TestProtected extends T
{
public void method(){
System.out.println(k);
}
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Can you guys tell me how I can access class T in package m?
The issue here is not related with public, I have tried, to be more general, what if you only have class T instead of its java code? The situation is you can access the T class without package, but you cannot access it with package.

You should make your class T public. Otherwise, it is not visible to classes in different packages.
You'll have to move T to a separate file, since you can't have multiple top level public classes in the same file.
Finally, your TestProtected class located in pacakge m should import the T class.

Related

How to access static block variables outside of class in java [duplicate]

This question already has answers here:
What is the scope of variables declared inside a static block in java?
(4 answers)
Closed 3 years ago.
I was working on some code in which I need to access the variable "hs" present in the static block of one class from another.
Note: Both the class are preset in different packages.
Code is as follow:
public class A{
static {
HashSet<String> hs = new HashSet<>();
}
}
I Googled about it but nothing found anything helpful.
Your help would be very appreciable.
EDIT: I am not allowed to make changes in this file still need to access it from the other file.
Why I need to do this cause I am doing unit testing by JUnit and there is nothing what this block is returning which I can put assertEquals() on. So the option I left with is to test the side-effects and this variable "hs" value is getting changed as a side-effect. That's why I need to access it from another file.
Declare it as public static inside the class and initialize it in static block
class A1{
public static HashSet<String> hs;
static {
hs= new HashSet<>();
}
}
Need create getter and setter for variable "hs".
Class 1:
public class Test {
public static HashSet<String> hs;
static {
hs = new HashSet<>();
hs.add("Test14");
hs.add("Test15");
hs.add("Test16");
}
public static HashSet<String> getHs() {
return hs;
}
public static void setHs(HashSet<String> hs) {
Test.hs = hs;
}
}
Class 2
If you need to use "hs" variable in without static method then:
public class Test2 {
public void test() {
Test ts = new Test();
ts.getHs();
}
}
If you need to use "hs" variable in with static method then:
public class Test2 {
public static void test() {
Test.getHs();
}
}

Java access static nested class [duplicate]

This question already has answers here:
Java inner class and static nested class
(28 answers)
Closed 5 years ago.
How can i create a instance of the following Class and access its methods.
Example:
public class A {
public static class B {
public static class C {
public static class D {
public static class E {
public void methodA() {}
public void methodB(){}
}
}
}
}
}
You can use :
A.B.C.D.E e = new A.B.C.D.E();//create an instance of class E
e.methodA();//call methodA
e.methodB();//call methodB
Or like #Andreas mention in comment you can use import A.B.C.D.E;, so if your class is in another packager then you can call your class using name_of_package.A.B.C.D.E like this:
import com.test.A.B.C.D.E;
// ^^^^^^^^------------------------name of package
public class Test {
public static void main(String[] args) {
E e = new E();
e.methodA();
e.methodB();
}
}

Access public static class' state from a separate class file

I have a public static class within another public class as follows:
public class Foo<A> {
public static class Bar<A>{
A firstBar;
Bar(A setBar){
this.firstBar=setBar;
}
}
public final Bar<A> instanceBar;
public Foo(A actualValue) {
instanceBar = new Bar<A>(actualValue);
}
public Bar<A> getBar() {
return instanceBar;
}
My objective is to access instanceBar's state from a separate class file without a get method and without changing the visibility of firstBar. How do I accomplish this?
For example, the following says not visible.
public class RetrieveFirstBar {
public static void main(String[] args) {
Foo z = new Foo(5l);
Foo.Bar<Long> z2 = z.getBar();
long k = z2.firstBar; //not visible!
}
}
I guess you mean
class Foo<A>
Since you write "A firstBar;" you give package access to the variable:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If you have the RetrieveFirstBar in the same package you will not have visibility problems. But, if you want to access it from everywhere you should write
public A firstBar;

why can't I create a method in the main method [duplicate]

This question already has answers here:
Writing a function inside the main method - Java
(7 answers)
Closed 6 years ago.
Hello I am a want create method into main?
So this is code where i want crete method:
import java.io.*;
import java.util.Random;
class input{
public static void main (String args[]){
void Randomises() {
int writabledata;
Random a=new Random();
writabledata=a.nextInt();
}
}}
Java does not allow to create methods within a method. This is a general rule and NOT specific to main method.
Perhaps what you are looking for is to create additional static methods in your class:
public final class MyCommand {
private MyCommand() {
//
}
private static void releaseTheCatsOfWar() {
System.out.println("Meow!");
}
public static void main(String[] args) {
releaseTheCatsOfWar();
}
}
Of course, it would be better to do:
public final class MyCommand {
private MyCommand() {
//
}
private void releaseTheCatsOfWar() {
System.out.println("Meow!");
}
public static void main(String[] args) {
MyCommand that = new MyCommand();
that.releaseTheCatsOfWar();
}
}
you cannot create methods within methods in Java.
You can have it as an additional method of your class and call it form main.
public static void main is not a class, it's a method within class. And your class is input (by the way, you should start class name with an uppercase letter, like Input), in which you define method main, from which your program starts working.
Although it is entirely pointless, the closest way you would get to achieving your results is with the following:
public class Main {
private static interface MethodMaker{
void randomise();
}
public static void main(String[] args) {
MethodMaker methodMaker = new MethodMaker(){
#Override
public void randomise() {
// DO SOMETHING
}
};
methodMaker.randomise();
}
}
You have to put method outside main ,, and just call it in main ,, like this :-
import java.io.*;
import java.util.Random;
class input{
public static void main (String args[]){
Randomises();
}
public void Randomises() {
int writabledata;
Random a=new Random();
writabledata=a.nextInt();
}
}

Java: Parent Methods accessing Subclasses' static variables?

I am trying to understand my way around polymorphism in Java. I created a parent class that has too many common methods that all children will use in the same manner.
Each of the subclasses' children all share static information, These variables or information will be used in the methods declared only in the parent.
The problem wish accessing static variables from Parent methods seems not really possible,
Its a solution to declare the common information per instance but since there will be 1000s of instances its such a waste of memory.
A simple elaboration of what i mean is the following code :
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
static
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
static
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
the output i expect was
1
2
1.
but what happens is :
1
2
2
One might think that on the initiation of each subclass the static variables of this subclass is set and then all methods referring to this subclass has access to the corresponding 'k' value.
But what actually happens is that all subclasses edit in the same static variable that is shared along all subclasses and hence destroys my whole point of using static variables for each subclass and its instances and using commmon methods in the Parent accessing these variables.
Any idea how can this be done ?
An option is to access the subclasses' static data through an abstract (non-static) method:
abstract public class Parent {
protected abstract int getK();
public void print() {
System.out.println(getK());
}
}
public class Child1 extends Parent {
private static final int CHILD1_K = 1;
protected int getK() { return CHILD1_K; }
}
public class Child2 extends Parent {
private static final int CHILD2_K = 2;
protected int getK() { return CHILD2_K; }
}
When you make new testChild2().print(); the static block on testChield2 was executed and change the value to 2.
static blocks only execute once when loaded by the ClassLoader.
This one give the output you want:
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Non static code blocks execute everytime the class is instanciated.
Premature optimization is the root of all evil. I don't think you'll run into any memory issues with thousands of instances, each with their own data, unless you're working on a tiny embedded system of some kind. Static variables are not intended to do what you're trying to do with them.
Static variables are specific to the class itself. If you want the same field in different instances of a class to have different values, then that field cannot be static.
The solution: don't make k static.
class testParent {
int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
this.k =2;
}
}
class testChild1 extends testParent{
{
this.k = 1;
}
public static void main(String[] args){
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Demo
(ignore the static class business - that's just to make it work in ideone).

Categories