How to get class'es method without importing class - java

There is a situation:
package pak1 contains some class
package pak1;
public class A {
public void g() {}
}
and another package pak2
package pak2;
public class B {
public void f() {
// here I want to call method g() from class A
}
}
Is there any way to call class's A method g() without importing class A (and then new A().g())?
If the method g() was static, I could write
public void f() {
pak1.A.g();
}

you can use fully qualified class name like:
pak1.A a = new pak1.A();
a.g();

Short answer: no, you need to import it.
Having said this, you could still execute A.g() without importing if you use refection API. Keep in mind that would add unnecessary complexity to your code.

As you said its possible only for static imports but otherwise its not possible.
Example of static imports is below where assertEquals is method under Assert class
import static org.junit.Assert.assertEquals;

I found answer from SMA a bit confusing. Here is another way to write it that may help explain the syntax:
// Use Scanner.nextLine() without import
class InputClass {
public static String getString() {
String bob = new java.util.Scanner(System.in).nextLine();
return bob;
}
}

Related

How to import functions from different files in Java [duplicate]

This question already has answers here:
Calling static method from another java class
(3 answers)
Closed 1 year ago.
In java, I know I can use methods from other class by creating that class in my main myClass newClass = new myClass() and then use methods by doing myClass.myMethod(), where myMethod() is defined in myClass.java, but what if I want a file named utils.java that contains a bunch of useful methods, I just want to use a function that there's in this file, is this possible? How can I import and use the functions from that file?
You do not need to "import" the functions, you would need just to create a class that keeps all your needed functions, and import that class.
I am supposing you use an IDE, you could go to your IDE and create a simple class.
e.g:
public class Utils
{
public static int doSmth(/* Your parameters here */)
{
// Your code here
}
public static void yetAnotherFunction(/* Your parameters here */)
{
// Your code here
}
}
The most important keyword here is static, to understand it I suggest you check my answer here: when to decide use static functions at java
Then you import this class to any of your other classes and call the static functions, without creating an Object.
import package.Utils;
public class MainClass
{
public static void main(String[] args)
{
Utils.doSmth();
}
}
You can add at the beginning:
import
like-
import utils;
Assuming it is in the same package as the current class
Else it should be:
import <package name>.<class name>
Yes, you can import methods but there are caveats. The methods are defined on a class. The methods are defined as static. The import employs the keyword static. Keep in mind that importing methods directly can create confusion and complicate debugging. Consider importing the class and invoke the method from the class. When/whether defining a utility class makes sense and how to implement them are separate discussions.
package some.path;
public class MyUtils {
public static int add(int x, int y) { return x + y; }
}
To import the method
package some.other.path;
import static some.path.MyUtils.add; // note keyword static here
public class MyClass {
private int a, b;
public int sum() { return add(a,b); }
}
Or, import the class and use the method statically
package some.other.path;
import some.path.MyUtils;
public class MyClass {
private int a,b;
public int sum() { return MyUtils.add(a,b); }
}

Package private access modifier

If a class has the visibility package private, is there any point to also set the methods to have that visibility since you can't access the methods in the first place?
The package private class for example may implement some interface and be used outside of its package. In that case implemented methods should be public. Also you might what to restrict usage of some members in the same package by private access modifier.
package pkg1;
public interface SomeInterface {
void m();
public static SomeInterface getImplementation() {
return new A();
}
}
class A implements SomeInterface {
#Override
public void m() {}
public void m2() {} // this one cannot be called from other packages
private void m3() {} // this one might be used only in class A
}
package pkg2;
import pkg1.SomeInterface;
public class Main {
public static void main(String[] args) {
SomeInterface implementation = SomeInterface.getImplementation();
implementation.m();
}
}
Simple answer yes if a class is going to be implemented or extend. No if it is not going to be extend or implemented. How ever I highly recommend to still make methods or variables you don't want other classes to see be private. This will save time later on if you wish to change the classes visiablity, along with making the code more readable in the long run.

Using static methods in static utility class in Java

I have a program in Java which use an helper class with static methods in the main class, as described:
public class MainClass {
public main() {
String abc = "xyz";
ResultA = Helper.methodA(abc);
ResultB = Helper.methodB(ResultA);
}
}
and the Helper:
public class Helper {
public static Result methodA(String s) {
...
}
public static Result methodB(Result r) {
...
}
}
Now, as you can see from the structure, there is a dependency of data between methodA and methodB in the helper, and I don't create any instance of class 'Helper'. Is that a proper use in static method as I have no validation of data here? Is there a better known structure for that case?
Would appreciate any help, thanks.
Better to use static methods as and when really needed. Utility classes having the static methods which share the common behaviour across the project.
If your method resides in the Utility class , then go ahead. Otherwise create object and access via in it.

Is there any reason for public methods in a package protected class?

I wonder if it makes any difference if a method is public or package protected in a class that is package protected.
class Example {
public void test() {}
}
instead of
class Example {
void test() {}
}
I guess the maximum visibility is given by the class. And a method can only reduce the visibility and increasing the visibility has no effect.
But it's valid syntax, so perhaps I've overseen something?
If we subclass Example to a public class , then code outside the package can access test() method using the subclass instance if it is public .
Example:
package A;
class Example {
public void test() {}
}
package A;
public class SubExample extends Example {
}
package B;
import A.SubExample;
class OutsidePackage {
public void some method(SubExample e){
// Had test been defined with default access in class Example
// the below line would be a compilation error.
e.test();
}
}
If Example implemented an interface of some kind you'd have to make them public, because you can't reduce access in that case. All interface methods are, by default, public.
As written, it does nothing. If it's a subclass or interface implementation, then it may be implementing or overriding methods that are declared public elsewhere.

Does the super class not call the overridden method?

I have the following classes:
class foo {
public void a() {
print("a");
}
public void b() {
a();
}
}
class bar extends foo {
public void a() {
print("overwritten a");
}
}
When I now call bar.b() I want it to call the overridden method a() in foo. It does, however, print "a".
Are your two classes in different packages? And is your foo class methods declared public, protected, or private or package local? Obviously if they are private, this won't work. Perhaps less obvious, is if they are package local (i.e. no public/protected/private scope) then you can only override them if you are in the same package as the original class.
For example:
package original;
public class Foo {
void a() { System.out.println("A"); }
public void b() { a(); }
}
package another;
public class Bar extends original.Foo {
void a() { System.out.println("Overwritten A"); }
}
package another;
public class Program {
public static void main(String[] args) {
Bar bar = new Bar();
bar.b();
}
}
In this case, you will still get 'A'. If you declare the original a() method in Foo public or protected, you will get the result you expected.
It may be that you are trying to use static methods, which won't work as they don't get overridden.
A good way of checking is to add the #Override annotation to bar.a() and see if the compiler gives you an error that a() isn't actually overidding anything
When I run the following:
public class Program {
public static void main(String[] args) {
bar b = new bar();
b.b();
}
}
class foo {
public void a() {
System.out.printf("a");
}
public void b() {
a();
}
}
class bar extends foo {
public void a() {
System.out.printf("overwritten a");
}
}
I get the following output:
overwritten a
which is what I would expect to see.
Are the methods defined as static? That's the only way I could see getting that result. I found a good explanation about that here: http://faq.javaranch.com/view?OverridingVsHiding
You may be confused if you are coming from C# or some other language where you have to explicitly declare virtual functions and/or overriding functions.
In Java, all instance functions are virtual, and can be overridden -- unless they are declared as private and/or final.
It is not necessary to specify the new #Override annotation to do so, adding the annotation just specifies that your intent is to override, and will cause a either a warning or error if it isn't an override. (If you accidentally misspelled the method name for example).
Andrew's example shows how this should work.
From the horse's mouth:
http://download.oracle.com/javase/tutorial/java/IandI/override.html
"The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass."
So if they are both static methods and you invoke the method from the super class, then the super class method is invoked, not the subclass method. So really, no overriding is taking place.
While I was working on an Android program, I had the same problem on my Java classes. It turned out that the problem was not in the classes but the way Android framework processes screen output.
for example if output was programmed in the onCreate() method in the parent class, Android failed to correctly fetch the output of overridden methods from child classes beyond first child. Honestly I don't understand whole method calling order.
To resolve the issue I simply programmed the output in the onResume() and now it seem to work fine.

Categories

Resources