How to use variables declared in another class? - java

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.

Related

Is it possible to access a private static variable and method?

We can access a static property of a class by writing className.propertyName, but if the property (method/variable) is private then is it possible to access that property?
For example,
class A{
static int a = 50;
}
public class HelloWorld{
public static void main(String []args){
System.out.print("A.a = ");
A obj = new A();
System.out.println(A.a);
}
}
This will print A.a = 50
But if I change static int a = 50; to private static int a = 50; then can I access that variable any how?
The private keyword means that it'll only be visible within the class. So in your example it means that you cannot access it like A.a. What you can do though is to create a public method that returns a.
private static int a = 5;
public static int getA () {
return a;
}
You can then statically call this method and retrieve the private static field.
// ...
System.out.println(A.getA());
Usually private static fields are rarely used though.
One more thing I'd like to add is the general use of static here.
As you actually create an instance of the class A the static modifier is redundant.
You cannot access the private in outside class or outside the package .Because private making them only accessible within the declared class.if you want to access the variables in the class means public,default and protected are only accessible .outside the package
means default is not possible only public and protected is possible ,protected also have different package and non sub class means not possible only sub class is possible(need to extend the class).public only accessible for all inside and outside the packages.

differences between "this" and "super" when accessing inherited members

I'm new to java. Recently I saw some code which was similiar to this:
class A {
protected int myInt;
public static void main(String[] args) {
B b = new B();
b.myFunction();
}
}
class B extends A {
public void myFunction() {
this.myInt = 10;
}
}
As far as I know, when creating a subclass instance, an instance of its parent is created as well. All protected and public members of base class are accessible from the subclass.
If I override myInt there will be a difference between this.myInt to super.myInt because each class will have its own myInt (B will have access to both).
So, my question is: if I don't override myInt, which form is preferable, this.myInt or super.myInt?
You only need to use this or super when need to specify which scope are you using/referring to. In your case, I'll prefer to omit the this to simplify the readability.
super is used to represents the current instante of a parent class while this is used to represents the current class. You only need to used this or super if some variable or method overlaps (Have the same name) with one in a wide scope.
eg. If you have define a method parameter with the same name as class attribute, you need to use this to indicate that you are using the class attribute and not the method parameter.
public class A {
public int myInt = 1;
public static void main(String[] args) {
B b = new B();
b.myFunction(3);
}
}
class B extends A {
public int myInt = 2;
public void myFunction(int myInt){
System.out.println(myInt); // The parameter
System.out.println(this.myInt); // myInt from the current class (B)
System.out.println(super.myInt); // myInt from the parent class (A)
}
}
This example will print:
3
2
1
If you don't have this kind of collission, the use of this is optional:
public void myFunction2(){
System.out.println(myInt); // Both refers to the same
System.out.println(this.myInt); // variable myInt from class B
}
It's a matter of taste and the project's standards/guidelines more than anything else.
Personally, I wouldn't use either, and would just write myInt = 10.
Only one instance is created. If you instantiate a derived object, the parents constructor is called, but only one object is created. Also, the term this is more so used when there are different variables with the same name being referenced in a class.
For example a simple constructor:
class SupClass{
public int a = 1;
int incA(){
return ++a;
}
}
class MyClass extends SupClass {
public int a = 10;
public int b = 20;
MyClass() {};
MyClass(int a, int b){
this.a = a;
this.b = b;
}
int incA(){
return ++a;
}
public static void main(String args[])
{
SupClass d = new MyClass();
System.out.println(d.a); //1, members known of type SupClass at compile-time,
System.out.println(d.incA()); //11, methods are virtual, decided at run-time
}
}
Only use the super method when you want to explicitly use the value that is in the super class. To answer your question, only methods can be overwritten, member variables can not.

why it is possible to get access to private field in static method if you pass object as parameter

For example I've got simple class
class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + obj.i);
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}
Why I can get access to i in static method?
private members can be accessible with in the class. Your static method belongs to the same class. Hence you can access.
Modifier Class Package Subclass World
---------------------------------------------
private **Y** N N N
Update: To avoid the confusion, move the static method to other class and try once.
Don't get confused with static and private/public/[default]. Those are two separate things. A static function can access private non-static field because it is part of the class. And thats whats private does, only restricting access to the class level, without any distinction being made between static or not.
If it's the staticness that's bothering you, obj is a proper "not static" object, which us why it has an accessible non-static field. The method being static is irrelevant.
you are accessing instance of object not directly class variable. when you use direly "i" without reference to object its not allowed.
Private variable visibility is by default in with in class access .
public class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + i); //compile Error ::Cannot make a static reference to the non-static field i
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}

Why I can not assign the value in public location in java

public class Test {
int a=10;
a=20;
}
why I can not assign the value as above;
When you declare an instance variable (class member) like this:
public class Test {
int a=10;
}
it means that any instance of class Test will have its own copy of this variable and it will be instantiated to 10.
Java allows an assignment upon declaration of instance variables, but after the variable was already declared it can be assigned only in:
an initializer block
a constructor
a method
which is why the second line will fail to compile.
The value would need to be static or inside of a method to assign the value in this portion of a class. You won't be able to change the value of a in that way unless you declare a static block of code.
try:
public class Test {
private static int a = 20;
}
or
public class Test {
private int a = 10;
public static void Main(String[] args) {
a = 20;
}
or
public class Test {
static {
int a = 10;
a = 20;
}
Try this. It is called initialization block
public class Test {
int a=10;
{a=20;}
}
EDITED:
You can alter variables values only in methods. Java is objective language not procedural.

Example of an instance method? (Java)

I'm still learning about methods in Java and was wondering how exactly you might use an instance method. I was thinking about something like this:
public void example(String random) {
}
However, I'm not sure if this is actually an instance method or some other type of method. Could someone help me out?
If it's not a static method then it's an instance method. It's either one or the other. So yes, your method,
public void example(String random) {
// this doesn't appear to do anything
}
is an example of an instance method.
Regarding
and was wondering how exactly you might use an instance method
You would create an instance of the class, an object, and then call the instance method on the instance. i.e.,
public class Foo {
public void bar() {
System.out.println("I'm an instance method");
}
}
which could be used like:
Foo foo = new Foo(); // create an instance
foo.bar(); // call method on it
class InstanceMethod
{
public static void main(String [] args){
InstanceMethod obj = new InstanceMethod();// because that method we wrote is instance we will write an object to call it
System.out.println(obj.sum(3,2));
}
int f;
public double sum(int x,int y){// this method is instance method because we dont write static
f = x+y;
return f;
}
}
*An instance method * is a method is associated with objects, each instance method is called with a hidden argument that refers to the current object.
for example on an instance method :
public void myMethod {
// to do when call code
}
Instance method means the object of your class must be created to access the method. On the other hand, for static methods, as its a property of Class and not that of its object/instance, it is accessed without creating any instance of the class. But remember static methods can only access static variables, where as instance method can access the instance variables of your class.
Static methods and static variables are useful for memory management as it does not require to declare objects which would otherwise occupy memory.
Example of instance method and variable :
public class Example {
int a = 10; // instance variable
private static int b = 10; // static variable (belongs to the class)
public void instanceMethod(){
a =a + 10;
}
public static void staticMethod(){
b = b + 10;
}
}
void main(){
Example exmp = new Example();
exmp.instanceMethod(); // right
exmp.staticMethod(); // wrong..error..
// from here static variable and method cant be accessed.
}
Instance methods are the methods that require an object to access them where as static methods do not. The method that you mentioned is an instance method since it does not contain static keyword.
Example of instance method:
class main
{
public void instanceMethod()//instance method
{
System.out.println("Hello world");
}
}
The above method can be accessed with an object:
main obj=new main();//instance of class "main"
obj.instanceMethod();//accessing instance method using object
Hope this might help you.
Instance block with Cases { Static , constructor , Local method )
OutPut will be :

Categories

Resources