Can I multiply a static and a non static variables, like this:
public class C {
protected int c;
private static int s;
public int ma() { return this.c*this.s; }
}
Or:
public class B{
protected int x;
private static int y;
public static int ms() { return x + y; }
}
The second code is not working and I am wondering is it because it's expecting static?
The second block of code is not working because ms is static. You cannot reference non-static members (x) from a static context.
You need to either make ms a non-static function or make x a static variable.
Like this:
public class B{
protected static int x; // now static
private static int y;
public static int ms() { return x + y; }
}
Or like this:
public class B{
protected int x;
private static int y;
public int ms() { return x + y; } // now non-static
}
A static variable/function is one that is shared across the application. In your second example
public class B{
protected int x;
private static int y;
public static int ms() { return x + y; }
}
Your method is declared static and is therefore a static context. Rule of thumb: You can't access non-static things from a static context. Here is some reasoning as to why that is.
Say you have two objects of type B one where x=1 and one where x=2. Since y is static it is shared by both objects. Let y=0.
Suppose from somewhere else in your program you call B.ms(). You're not referring to any particular B object. Therefore the JVM is unable to add x + y because it doesn't know what value of x to use. Make sense?
Related
I have three static methods each in their own public classes. Simple arithmetic methods to help me learn.
The methods use three variables that when defined as static int variables in the main method. The program works.
Now according to my understanding of what I have read, I should be able to move the variable definition to another class and define them as public. The main method in its own public class should then be able to find these definitions and run. But this does not happen. Instead my eclipse workspace reports that the definitions cannot be resolved to a variable.
Here is the very simple code (which gives me the compilation error):
package christmas;
public class addintegers {
public int number1 = 5;
public int number2 = 10;
public int answer;
public static int add2numbers(int a, int b) {
return (a + b);
}
}
class 2
package christmas;
public class subtractintegers {
public static int sub2numbers(int a, int b) {
return (a - b);
}
}
Then I have my main method. This is where I am getting the compilation error.
package christmas;
public class glue {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(addintegers.add2numbers(number1, number2));
System.out.println(subtractintegers.sub2numbers(number1, number2));
answer = (addintegers.add2numbers(number1, number2)) + (subtractintegers.sub2numbers(number1, number2));
System.out.println("answer =" + answer);
}
}
the errors I get are:
>create local variable number1
>create local variable number2
>create local variable answer
First off:
Class names should be nouns, and use UpperCamelCase
Method names should be verbs, and use lowerCamelCase
E.g., something along the lines of:
public class Addition {
public static int add(int a, int b) {
return a + b;
}
}
public class Subtraction {
public static int subtract(int a, int b) {
return a - b;
}
}
If you want to have number1, number2, and answer fields in the class that I renamed Addition, normally what you would do is make them private instance variables and expose them through getters:
public class Addition {
private int number1 = 5;
public int getNumber1() {
return number1;
}
}
You can then access them by creating an instance of the class, e.g.: new Addition().getNumber1();. Since the Addition and Subtraction classes seem to be utility classes however, perhaps it makes more sense to declare these fields private static so you won't have to instantiate the classes:
public class Addition {
private static int number1 = 5;
public static int getNumber1() {
return number1;
}
}
You can then access them by referencing the class as opposed to an instance of the class, e.g.: Addition.getNumber1();.
You are almost there. You are missing 2 key points:
To share the variables number1, number2 and answer without instantiating the addIntegers class, you need to make them static.
To access the variables number1, number2 and answer from within the glue class' main method, you need to prefix the variables with the addIntegers class.
package christmas;
public class addintegers {
public static int number1 = 5;
public static int number2 = 10;
public static int answer;
public static int add2numbers(int a, int b) {
return (a+b);
}
}
package christmas;
public class glue {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(addintegers.add2numbers(addintegers.number1,addintegers.number2));
System.out.println(subtractintegers.sub2numbers(addintegers.number1,addintegers.number2));
addintegers.answer = (addintegers.add2numbers(addintegers.number1,addintegers.number2))+(subtractintegers.sub2numbers(addintegers.number1,addintegers.number2));
System.out.println("answer =" +addintegers.answer );
}
}
package com.rohov;
public class Application {
public static void main(String[] args) {
System.out.println(AddInteger.sum(AddInteger.num1, AddInteger.num2));
System.out.println(SubInteger.sub(AddInteger.num1, AddInteger.num2));
AddInteger.sum = AddInteger.sum(AddInteger.num1, AddInteger.num2) + SubInteger.sub(AddInteger.num1, AddInteger.num2);
System.out.println(AddInteger.sum);
}
}
class AddInteger {
public static int num1 = 5;
public static int num2 = 10;
public static int sum;
public static int sum(int a, int b) {
return a + b;
}
}
class SubInteger {
public static int sub(int a, int b) {
return a - b;
}
}
This question already has answers here:
Can a constructor in Java be private?
(16 answers)
Closed 4 years ago.
newbe question. Does it make any sense to have a private constructor in java with parameters? Since a private constructor can only be accessed within the class wouldn't any parameters have to be instance variables of that class?
Yes, if you are going to use that constructor in some method of your class itself and expose the method to other class like we do in the singleton pattern. One simple example of that would be like below :
public class MySingleTon {
private static MySingleTon myObj;
private String creator;
private MySingleTon(String creator){
this.creator = creator;
}
public static MySingleTon getInstance(String creator){
if(myObj == null){
myObj = new MySingleTon(creator);
}
return myObj;
}
public static void main(String a[]){
MySingleTon st = MySingleTon.getInstance("DCR");
}
}
Suppose that you have multiple public constructors with the same variable to assign to a specific field or that you need to perform the same processing, you don't want to repeat that in each public constructor but you want to delegate this task to the common private constructor.
So defining parameters to achieve that in the private constructor makes sense.
For example :
public class Foo{
private int x;
private int y;
public Foo(int x, int y, StringBuilder name){
this(x, y);
// ... specific processing
}
public Foo(int x, int y, String name){
this(x, y);
// ... specific processing
}
private Foo(int x, int y){
this.x = x;
this.y = y;
}
}
There is a keyword this in java to access the instant variables which are public. But is there such way to access the private ones
class Foo {
private int a = 2;
public int b = 3;
public void test(int a, int b) {
this.b = b;
//but how to access a;
}
public static void main(String args[]) {
Foo x = new Foo();
x.test(1, 2);
}
}
Above is the code example I have....
Within the same class, both private and public variables can be accessed in the same way:
class Foo {
private int a = 2;
public int b = 3;
public void test(int a,int b){
this.b = b;
this.a = a; // accessing private field a
}
public static void main(String args[]){
Foo x = new Foo();
x.test(1,2);
}
}
All class methods have access to their own private members. Hence, this.a = a will work.
Follow Java tutorial on this keword it can access private members:
private int x, y;
public Rectangle(int x, int y, int width, int height) {
this.x = x;
A class object can access it's private members, otherwise nothing could access them and they'd be quite pointless. So this with private members works absolutely fine.
Class method have an access to private data member so you can use
this.a=a
I was playing around with classes since I'm learning java syntax and I came across this weird situation. So given a class A and B:
public class A {
public int x() {
return x;
}
}
public class B extends A {
int x = 5;
public int x() {
return x + 2;
}
public static void main(String[] args) {
B b = new B();
System.out.println(b.x());
}
When I execute the main method I get a compile time error that it doesn't find the x variable and it's calling the method from A because the error shows return x instead of return x + 2. Since b's static type is B, why is it looking in A for x?
error: cannot find symbol
return x;
symbol: variable x
location: class A
The class A doesn't know that it will be extended by B, where the x variable will exist.
In order to make this compile, make A.x() abstract and provide implementation within the subclass:
public abstract class A {
public abstract int x();
}
public class B extends A {
int x = 5;
#Override
public int x() {
return x + 2;
}
..
}
When you are creating the Object of class B, it automatically invoke the x() of class A, But x is not initialized in that class. As it is a local variable, it can not be used without initialization. so it is giving an error.
Try the below code, it is working correctly
class A
{
int x =10;
public int x()
{
return x;
}
}
class B extends A
{
int x = 5;
public int x()
{
return x + 2;
}
public static void main(String[] args)
{
B b = new B();
System.out.println(b.x());
}
}
public abstract class SuperClass {
public int x, y;
public static int z;
}
I want every subclass of SuperClass to have the static variable z. Naturally z will contain a different value for each subclass. I'm hoping to avoid defining z in every subclass, since it's going to be a functional dependancy of values x and y; Is this possible?
Unlike instance variables that are "one per instance", static variables are not "one per subclass" - they are "one per declaring class". In other words, subclasses of SuperClass share SuperClass.z, but they cannot "override" it on a class-by-class basis.
It does not mean that you cannot implement it yourself: on way to make your own per-subclass storage of integers is adding a static Map<Class,int> zs to SuperClass, with optional functions for accessing the data:
public abstract class SuperClass {
public int x, y;
private static Map<Class,Integer> zs = new HashMap<Class,Integer>();
protected static int getZ(Class c) {
Integer res = zs.get(c);
return res == null ? -1 : res.intValue();
}
protected static void setZ(Class c, int v) {
zs.put(c, v);
}
}
class SubClassOne extends SuperClass {
public int getZ() {
return SuperClass.getZ(SubClassOne.class);
}
}
class SubClassTwo extends SuperClass {
public int getZ() {
return SuperClass.getZ(SubClassTwo.class);
}
}
Probably the best way to do this is to have a z() method or similar in the abstract class, and override the method in the subclasses you want.
Example:
public abstract class SuperClass {
public int x, y;
protected int z() {
return 42; // protected so only subclasses can see it - change if required
}
}
public class SubClassOne extends SuperClass {
public void foo() {
// do something...
int z = z();
// something else...
}
}
public class SubClassTwo extends SuperClass {
#Override
protected int z() {
return 1;
}
// use z() accordingly
}
if i understand you correctly then do
public abstract class SuperClass {
public int x, y, z;
public SuperClass(int z) {
this.z = z;
}
}
then any class that extends this class inherits z;