Hi I was looking at this syntax from the Android API and found it a bit weird.
java.lang.Object
↳ android.graphics.BitmapFactory.Options
public static class
BitmapFactory.Options
I have never seen a class with a '.' in the middle of it. Why didn't they just call the class 'BitmapFactoryOptions'?
Then I was confused even more because I saw this code in a book
final BitmapFactory.Options options = new BitmapFactory.Options();
BitmapFactory is static yet we are creating an instance of it?
Adding to #dasblinkenlight answer, the code could look like:
public class BitmapFactory {
public static class Options {
}
}
And that's indeed the case, see source code for BitmapFactory.
They did not name the class with a dot in it (that would be illegal). All they did was adding a static inner class called Options - a member class of the BitmapFactory class.
This is a common way of hiding classes inside their outer classes when the class or an interface in question has no meaning on its own, and must be interpreted only in the context of its outer class.
Of course the solution that you suggested (naming the class BitmapFactoryOptions) is perfectly valid as well. However, it gives a false impression that the class can be useful on its own.
Perhaps the most commonly used example of this is the Map.Entry<K,V> interface: map entries have meaning only when there is a map around them, so the nesting is very useful.
Just like any other class variable and class method, there can be class within a class as well. The following example shows all three kinds of class members accessed using the same syntax.
public class Person{
public static long totalPopulation;
public static void calculateAge(Date dob){
}
public static class Address{
}
}
All of these will be accessed in the same way. i.e.,
Person.totalPopulation = 700_000_0000L;
Person.calculateAge(person.getDOB());
Person.Address address = new Person.Address();
Related
Hi I am trying to access a public object in another package within a project.
I am trying to access the 'opponent' object which is of type 'Character' in the Attribute class.
public class Engine {
public static Character opponent;
}
Class I am trying to access object in. "This class is in another package".
public int opponentAttackDamage() {
int attack = opponent.getAttribute().getAttack();
}
In order to access an static attribute from anywhere even in the same class where it's declared (as a good practice) you should use the name of the class follow by dot an the name of the attribute:
Engine.opponent.getAttribute().getAttack();
Also you should have in mind that opponent object must be initialized in somewhere in your class (opponent = new Opponent() - I guess - ).
If opponent is a static attribute of the Engine class, and the method you are accessing it from is not in the same class, you need to mention Engine.opponent to access it. Also, you need to import the package where Engine class is defined.
my annotation processor reads a class like this:
#Foo
public class Bar (){
}
Now I want to generate an inner class Bar$MyGeneratedClass so that at the end I have a class MyGeneratedClass that to the compiler / jvm looks like this:
public class Bar (){
// Generated by annotation processor
public static class MyGeneratedClass () { ... }
}
Is this possible? I think so, I guess I just have to name the generated class Bar$MyGeneratedClass right?
Does anybody know how to generate such a inner class with java poet?
You can use javapoet to create new classes. It's not possible modify existing class with javapoet.
On jvm level there is no such things as inner classes.
So while compiling both classes (the inner and the outer) are transfomed to simulate that effect.
The inner class gets a constructor parameter. With that parameter you need to pass in an instance of the outer class.
As both class types can access private members package private accessors are created.
Especially the second transformation requires you to change the outer class.
I am writing a Junit for a method with multiple parameters and having private access specifier. I am using Java reflection to achieve this. However, one of the parameter for this private method is private class. I am doing below:
ClassHavingPrivateMethod object = new ClassHavingPrivateMethod();
object.getClass().getDeclaredMethod(PRIVATE_METHOD_NAME, Param1.class, <This parameter is a private class Inside ClassHavingPrivateMethod>)
How can I proceed?
EDIT
I agree on the point that I should not write a test case for a private method with reflection and it should always be accessed through a wrapper public method. However, is there any way to achieve the above objective through reflection. Even though, I am not going to write my test case through reflection but I am eager to know about it.
Any help is really appreciated.
One of the way you can try by changing the access from private to default. By changing the access level to default the method can be accessed only from the same package (still restricted access) on the other hand since your test class and class under test will be under same package , the test class can call that method directly, without doing any trick.
Example :
package com.test;
class SomeClass {
String defaultMethod(){
...
}
}
package com.test;
class SomeClassTest {
public void testDefaultMethod(){
SomeClass testObject = new SomeClass();
testObject.defaultMethod();
}
}
Hope it will help.
I'm new to Java and i want a refinement:
First of all,i am not sure if i can have 2 classes in the same file.
My question is what is each class when you see this sequence of code:
class Something {
//code here
} //end of class Something
public class SomethingElse {
//NO code here!!!
public static void main(String[] args) {
//code of main here
}//end of main
}
What's the role of the class Something Else and why there is no code inside?I know that is a very stupid question but there are some details that i don't really get and i want some help...
You can have more than one class per file, but only one class can be public and its name must match the name of the file (e.g. public MyClass in MyClass.java).
The public class of a file will be visible to the outside world, and in particular if the class has a public static main(String[] args) method, it can be used to start an application.
In your case for example, once you have compiled your file using javac, you will get files Something.class and SomethingElse.class.
Using the command java SomethingElse will tell the Java Virtual Machine to do the following:
Find the SomethingElse class, which must be in the SomethingElse.class file
call the main method, matching the signature I pasted above on this class (and putting any given argument in the args array).
You cannot call java Something because the class isn't public and doesn't have a main method. But other classes in your program (and in particular, SomethingElse, can use your Something class).
You can have just one public class per file, and the file must have the same name of the class. But you can have other private classes that just the file class will see. For example:
File Something.java
public class Something {
//Something can access SomethingElse's doSomething method.
private class SomethingElse {
public void doSomething() {
}
}
}
class SomethingToo {
}
File OtherSomething.java
public class OtherSomething {
//OtherSomething cannot access SomethingElse's doSomething method.
//But can access SomethingToo, if they are in the same package
}
You can have multiple classes defined in a same file. However there should only one class defined as public and file name will be that public class name.
In the No code here!!! you can have class variables and methods defined. Your main() is one such example.
In the above file, there are two classes SomethingElse (public) and Something. Now, this is normally done when the non-public class is called internally by the public class. Also, in the above code fragment, SomethingElse seems to be a 'driver' class. In other words, it does not have any functionality/data of its own, but is used to execute (drive) other classes (probably Something in this case)
You can have nested classes, but two separate, public classes are not allowed. Each public class should be in it's own file named the same as the class.
While it's possible to have 2 classes in the same file, its considered bad practice. Besides the decreased readability, it will eventually become difficult to find out where that class declaration actually took place. Plus, if you declare a variable relating to the class, but not the class sharing the .java name, javac will most likely have issues compiling.
If you have to do it, make sure the only place you are using the second class is within the class sharing the .java name. (E.g. only use a Something object within the SomethingElse class). Otherwise, separate all your classes into separate .java files.
Yes, you can have 2 or more classes in single Java file.
The only condition is only one class will contain main method with signature(public static void main(String[] args)).
And only one public class will be there. And with that public class name you can save your file - the file name has to match the name of the public class.
is there a way we can import a class under another name?
Like if i have a class called javax.C and another class called java.C i can import javax.C under the name C1 and import java.C under the name C2.
We can do something like this in C#:
using Sys=System;
or Vb:
Imports Sys=System
No, there is nothing like that in Java. You can only import classes under their original name, and have to use the fully qualified name for all that you don't import (except those in java.lang and the current class's package).
To be short, no, this isn't possible in Java.
No. I think Java deliberately ditched typedef. The good news is, if you see a type, you know what it is. It can't be an alias to something else; or an alias to an alias to ...
If a new concept really deserves a new name, it most likely deserves a new type also.
The usage example of Sys=System will be frowned upon by most Java devs.
Java doesn't support static renaming. One idea is to subclass object in question with a new classname (but may not be a good idea because of certain side-effects / limitations, e.g. your target class may have the final modifier. Where permitted the code may behave differently if explicit type checking is used getClass() or instanceof ClassToRename, etc. (example below adapted from a different answer)
class MyApp {
public static void main(String[] args) {
ClassToRename parent_obj = new ClassToRename("Original class");
MyRenamedClass extended_obj_class_renamed = new MyRenamedClass("lol, the class was renamed");
// these two calls may be treated as the same
// * under certain conditions only *
parent_obj.originalFoo();
extended_obj_class_renamed.originalFoo();
}
private static class ClassToRename {
public ClassToRename(String strvar) {/*...*/}
public void originalFoo() {/*...*/}
}
private static class MyRenamedClass extends ClassToRename {
public MyRenamedClass(String strvar) {super(strvar);}
}
}