What's the difference between calling through and object vs class - java

What's the difference between calling a method through an object vs a class.
for example the Class Bob
public class SecretNumber() {
public static int secretNumber = 2;
public static void changeSecretNumber(){
secretNumber++;
}
}
What would be the difference if i called it like an object
SecretNumber secretNumber = new SecretNumber();
secretNumber.changeSecretNumber();
vs calling it like this
SecretNumber.changeSecretNumber();
How would one method effect the other?

The result is the same.
You should call it by class name, not through the instance, because no dynamic dispatch happens.
Most compilers will give you a warning, if you do that, too. Some people argue that it should have been made a compile error.

In Java, unless a class method is "static", you can't call it except through an object instance.
Here's an example of a method where it would make sense to declare it "static":
http://www.leepoint.net/notes-java/flow/methods/50static-methods.html
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

The second form isn't valid Java. You can only call methods on a class if they are declared static.

Calling a method through a class is a static method. Unless you declare the method a static method, the compiler will give you a compile error .

Related

Why Must this method be static(Java)?

For some background, I'm currently on chapter 8 in my book, we finished talking about arraylists, arrays, if statements, loops etc. Now this part of the book talks about call by reference,value and some other pretty neat things that seem odd to me at first.I've read What situation to use static and some other SO questions, and learned quite a bit as well.
Consider the following example my book gave (among many examples)
There is another reason why static methods are sometimes necessary. If
a method manipulates a class that you do not own, you cannot add it to
that class. Consider a method that computes the area of a rectangle.
The Rectangle class in the standard library has no such feature, and
we cannot modify that class. A static method solves this problem:
public class Geometry
{
public static double area(Rectangle rect)
{
return rect.getWidth() * rect.getHeight();
}
// More geometry methods can be added here.
}
Now we can tell you why the main method is static. When the program
starts, there aren’t any objects. Therefore, the first method in the
program must be a static method.
Ok, thats pretty cool, up until now I've just been really blindly putting public in front of all my methods, so this is great to know. But the review small problem on the next page caught my attention
The following method computes the average of an array list of numbers:
public static double average(ArrayList<Double> values)
Why must it be a static method?
Here I was like wait a sec. I'm pretty sure I did this without using static before. So I tried doing this again and pretty easily came up with the following
import java.util.ArrayList;
class ArrList
{
private double sum;
public ArrList()
{
sum = 0;
}
public double average(ArrayList <Double> values)
{
for(int i = 0; i < values.size() ; i++)
{
sum+=values.get(i);
}
return sum / values.size();
}
}
public class Average
{
public static void main(String [] args)
{
ArrList arrListObj = new ArrList();
ArrayList<Double> testArrList = new ArrayList<Double>();
testArrList.add(10.0);
testArrList.add(50.0);
testArrList.add(20.0);
testArrList.add(20.0);
System.out.println(arrListObj.average(testArrList));
}
}
TLDR
Why does my book say that public static double average(ArrayList<Double> values) needs to be static?
ATTEMPT AT USING STATIC
public class Average
{
public static void main(String [] args)
{
ArrayList<Double> testArrList = new ArrayList<Double>();
ArrayList<Double> testArrListTwo = new ArrayList<Double>();
testArrList.add(10.0);
testArrList.add(50.0);
testArrList.add(20.0);
testArrList.add(20.0);
testArrListTwo.add(20.0);
testArrListTwo.add(20.0);
testArrListTwo.add(20.0);
System.out.println(ArrList.average(testArrList));
System.out.println(ArrList.average(testArrListTwo)); // we don't get 20, we get 53.3333!
}
}
It doesn't.
The only method which needs to be static is the initial main() method. Anything and everything else is up to you as the programmer to decide what makes sense in your design.
static has nothing to do with public accessors (as you allude to), and it has nothing to do with the technical operation being performed. It has everything to do with the semantics of the operation and the class which holds it.
An instance (non-static) method exists on a particular instance of a class. Semantically it should perform operations related to that specific instance. A static method exists on a class in general and is more conceptual. It doesn't do anything to a particular instance (unless it's provided an instance of something as a method argument of course).
So you really just need to ask yourself about the semantics of the operation. Should you need new instance of an object to perform an operation? Or should the operation be available without an instance? That depends on the operation, on what the objects represent, etc.
If it is not static, then any other class that wants to use this method must first create an instance of this object.
From some other class:
Average.average(new ArrayList<Double>()); // legal only if static
new Average().average(new ArrayList<Double>()); // necessary if not static
// and only makes sense if Average can be instantiated in the first place
It's legal to make it an instance (i.e. not static) variable, but the method is actually harder to understand. If it is static then whoever reads the code knows it does not use any member variables of the class.
// In the class body
int x = 0; // member variable
public static double average() {
x = x + 1; // illegal
}
The less something can do, the easier to understand what it does do.
Static methods like the area, average are usually utility functions. You don't need any object to use an utility function. For example consider Math.pow you don't need to instantiate any object to use the power function, just use Math.pow(10.0, 2.0) to get (10.0)^2
In short :
Static method means class method, that is no instance of that object is needed to invoke.
whereas your average method is an instance method, you need an object to invoke that method.

About declaring and initializing primitive variable in different line outside a method

new to the community, and new to the whole programming world.
While I was studying java, I stumbled on a simple question.
In a main method (or any method), I can declare and initialize a primitive variable on different line just fine. Say,
public static void main (Strin[]args){
int age;
age = 42;
}
will complile just fine.
But if I tried this outside a method, as a class variable or instance variable,
public class test {
int age;
age = 42;
}
the code won't compile. It will only work if the variable is declared and initialized in one line. I was wondering why java doesn't allow this outside a method.
A class body can contain variable declarations and method declarations, but no single statements. When would you expect such a statement to be executed? So your initialization has to be either inline with the declaration (as a shortcut) or in some method, e.g. in the constructor, if you want to initialize the variable when creating a new object.
It is a syntax error! Your code does not comply with the Java syntactic and semantics rules as described in Java Language Specification.
You have to initialise it's value inside the constructor (that's the whole point of a constructor), like
public test() {
age = 42;
}
For static variables it's possible to give them a value:
static int age = 42;
Or use a static block:
static {
age = 43;
}

How to call a method from another class with no constructor

I'm having a bit of trouble on a program at school.
I have to call a method called factorial in my FactorialCalculator class through a method called factorial in my BCD class. Normally, I would do something like this:
FactorialCalculator newCalc = new FactorialCalculator(8);
However, factorial is the only method in the FactorialCalculator class, and I am not allowed to make any more methods, including a constructor.
Any suggestions?
Create it as a static method:
public class FactorialCalculator {
public static int factorial(int number) {
// Calculate factorial of number
}
}
And you can call it this way:
int factorial = FactorialCalculator.factorial(5); // for the example
A static method is a method that is not associated with any instance of any class, & it can be accessed using the Classname.staticMethod( ) notation.
It's Simple, if you make it Static, You will be able to call it from another class.
Create it as a static method:
class FactorialCalculator {
public static int factorial(int number) {
...YourCode...
}
}
And you can call it this way:
int number = 10;
int f = FactorialCalculator.factorial(number);
If it is a static method, you would do FactorialCalculator.factorial(...).
You can either use a default constructor, which is just FactorialCalculator fc = new FactorialCalculator();. Easy as that. However, it looks like your teacher wants you to create a static method. Static methods are sort of like utilities of a class, instead of being a function of an object. So, in your case, you should make FactorialCalculator be more of a utility class instead of an object class. public static int factorial(int num) {} should do the trick. This way, you can just go FactorialCalculator.factorial(5) as you did in your example.
Hope this helps!
First, you always have the standard constructor, which takes no parameters. So you can instatiate FactorialCalculator and then call its factoral-Method.

how to declare a helper method in java, to be used locally being able to reference variables

I have a class with several methods. Now I would like to define a helper method that should be only visible to method A, like good old "sub-functions" .
public class MyClass {
public methodA() {
int visibleVariable=10;
int result;
//here somehow declare the helperMethod which can access the visibleVariable and just
//adds the passed in parameter
result = helperMethod(1);
result = helperMethod(2);
}
}
The helperMethod is only used by MethodA and should access MethodA's declared variables - avoiding passing in explicitly many parameters which are already declared within methodA.
Is that possible?
EDIT:
The helper mehod is just used to avoid repeating some 20 lines of code which differ in only 1 place. And this 1 place could easily be parameterized while all the other variables in methodA remain unchanged in these 2 cases
Well you could declare a local class and put the method in there:
public class Test {
public static void main(String[] args) {
final int x = 10;
class Local {
int addToX(int value) {
return x + value;
}
}
Local local = new Local();
int result1 = local.addToX(1);
int result2 = local.addToX(2);
System.out.println(result1);
System.out.println(result2);
}
}
But that would be a very unusual code. Usually this suggests that you need to take a step back and look at your design again. Do you actually have a different type that you should be creating?
(If another type (or interface) already provided the right signature, you could use an anonymous inner class instead. That wouldn't be much better...)
Given the variables you declare at the top of your method can be marked as final (meaning they don't change after being initialized) You can define your helper method inside a helper class like below. All the variables at the top could be passed via the constructor.
public class HelperClass() {
private final int value1;
private final int value2;
public HelperClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int helperMethod(int valuex) {
int result = -1;
// do calculation
return result;
}
}
you can create an instance of HelperClass and use it inside the method
It is not possible. It is also not good design. Violating the rules of variable scope is a sure-fire way to make your code buggy, unreadable and unreliable. If you really have so many related variables, consider putting them into their own class and giving a method to that class.
If what you mean is more akin to a lambda expression, then no, this is not possible in Java at this time (but hopefully in Java 8).
No, it is not possible.
I would advise you create a private method in your class that does the work. As you are author of the code, you are in control of which other methods access the private method. Moreover, private methods will not be accessible from the outside.
In my experience, methods should not declare a load of variables. If they do, there is a good chance that your design is flawed. Think about constants and if you couldn't declare some of those as private final variables in your class. Alternatively, thinking OO, you could be missing an object to carry those variables and offer you some functionality related to the processing of those variables.
methodA() is not a method, it's missing a return type.
You can't access variables declared in a method from another method directly.
You either has to pass them as arguments or declare methodA in its own class together with the helpermethods.
This is probably the best way to do it:
public class MyClass {
public void methodA() {
int visibleVariable=10;
int result;
result = helperMethod(1, visibleVariable);
result = helperMethod(2, visibleVariable);
}
public int helperMethod(int index, int visibleVariable) {
// do something with visibleVariable
return 0;
}
}

Why am I having problems calling this method from a different class?

I am an eighth grader with a tight deadline on a java project. I have my GUI all ready to go, except I need to take the two values from the two text fields, and send them to a method in a different class when I press a button. I am having trouble calling the method I need. All important code is below.
Code that is attempting to call the method:
private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {
String Ntextfield = NumberTextField.getText();
n = Integer.parseInt(Ntextfield);
String Rtextfield = RateTextField.getText();
r = Integer.parseInt(Rtextfield);
//call PermMath class
PermMath doTheMath = new PermMath();
doTheMath.permutations(int n, int r);
}
Method I am trying to call:
class PermMath {
static long factorial(int num){
//other code is here
}
static long permutations(int n, int r){
//code I want to call is here
}
}
The hint for you is the static keyword. Learn what it means and how it works.
Also, you're using the variables n and r even before declaring them.
n = Integer.parseInt(Ntextfield);
should come after you've done something like int n = 0;.
And while invoking a method, you don't declare the parameters. The below is wrong.
doTheMath.permutations(int n, int r);
Instead you do something like
doTheMath.permutations(n, r);
It seems to me you have two mistakes:
You are passing two temporary integers called n and r instead of passing the two integers you modified earlier in your GoButtonActionPerformed function.
The permutations function is static, so there is no need to actually create an instance of the PermMath class.
Changing the function call to this should do it:
PermMath.permutations(n, r);
Note that if PermMath is in another package than the class which defines GoButtonActionPerformed(...) it won't be visible due to the lack of a public access modifier on the methods and even the class.
Btw, in Java method names should start with a lower case latter. While your style is valid code adhering to the convention makes it easier for other Java developers to read your code.
Another thing: you don't use the return value of permutations(...). That might not be intented.
You've declared static methods in your PermMath class - these do not require an instantiation of the class to be called. You simply call them with:
PermMath.permutations(n,r);
Check out the track for this at: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Categories