meaning of protected static A.B newvar = null - java

I was going throught a huge java project and I came across this line in a file.I am new to java and don't know what this means.Or more specifically
Should I look at PSStreamer.java OR Client.java to see the methods and member variables of the below object.
protected static PSStreamer.Client packetClient = null;

This is what's being declared:
protected // protected visibility modifier
static // a class (static) member
PSStreamer.Client // Client is an inner class of PSStreamer
packetClient = null; // variable name, null initial value
You should look inside PSStreamer to find the inner class Client, and that's where you'll find the attributes and methods of packetClient.

That is a static inner class.
It would look like this: (in PSStreamer.java):
class PSStreamer {
...
static class Client {
...
}
}

That is a static nested class. It should be defined in the source code as
public class PSStreamer {
public static class Client {
// ..
}
// ..
}
So, you should be looking inside PSStreamer.java. Read more about Nested Classes.
Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
Also, take a look at this SO link: Java inner class and static nested class

Related

android studio accepted importing inner class?

i have this code :
package com.example.android.cars.data;
public final class DataBaseContract {
public static final class Table1Entry implements BaseColumns {
/** Name of database table for cars */
public final static String TABLE_NAME = "car";
}
}
i use Table1Entry in another class with different package and i import the nested class like this
import com.example.android.cars.data.DataBaseContract.Table1Entry;
this allow me to use nested class without outer prefix DataBaseContract,
my question is when i removed static from nested class the code still work, how can this accrue in this case !! i need outer instance to access it!!
Yes you would need an instance of the outerclass IF you wanted to access instance methods of the inner class. However from your example you are only accessing static fields, therefore because the field is static you can access it directly like you explained.

Can I access an outer class instance from an instance of that outer classes inner class anonymously? [duplicate]

Say if I have a dropdown in a form and I have another nested class inside of this class .
Now what's the best way to access this dropdown from the nested class?
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
// C#
class OuterClass
{
string s;
// ...
class InnerClass
{
OuterClass o_;
public InnerClass(OuterClass o) { o_ = o; }
public string GetOuterString() { return o_.s; }
}
void SomeFunction() {
InnerClass i = new InnerClass(this);
i.GetOuterString();
}
}
Note that the InnerClass can access the "s" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "string s;" is private because no other access permission was specified.
Nested types aren't like inner classes in Java - there's no inherent instance of the containing type. (They're more like static nested classes in Java.) They're effectively separate classes, with two distinctions:
If the containing type is generic, the nested type is effectively parameterised by the containing type, e.g. Outer<int>.Nested isn't the same as Outer<string>.Nested.
Nested types have access to private members in the containing type.
Unlike Java, in C# there is no implicit reference to an instance of the enclosing class.
You need to pass such a reference to the nested class. A typical way to do this is through the nested class's constructor.
public partial class Form1 : Form
{
private Nested m_Nested;
public Form1()
{
InitializeComponent();
m_Nested = new Nested(this);
m_Nested.Test();
}
private class Nested
{
private Form1 m_Parent;
protected Form1 Parent
{
get
{
return m_Parent;
}
}
public Nested(Form1 parent)
{
m_Parent = parent;
}
public void Test()
{
this.Parent.textBox1.Text = "Testing access to parent Form's control";
}
}
}
Static Members
Since no one has mentioned it so far: Depending on your situation, if the member variable can also be static, you could simply access it in following way.
class OuterClass
{
private static int memberVar;
class NestedClass
{
void SomeFunction() { OuterClass.memberVar = 42; }
}
}
Sidenote: I marked memberVar purposefully (and redundantly) as private to illustrate the given ability of the nested class to access private members of it's outer class.
Caution / Please consider
In some situations this might be the easiest way/workaround to get access, but ...
Static also means, that the variable will be shared across all instance objects, with all the downsides/consequences there are (thread-safety, etc.)
Static also means, that this will obviously not work if you have more than one instance of the parent's class and the variable should hold an individual value for each instance
So in most cases you might wanna go with a different approach ...
Passing a Reference
As most people have suggested (and because it is also the most correct answer), here an example of passing a reference to the outer class' instance.
class OuterClass
{
private int memberVar;
private NestedClass n;
OuterClass() { n = new NestedClass(this); }
class NestedClass
{
private OuterClass parent;
NestedClass(OuterClass p) { parent = p; }
SomeFunction() { parent.memberVar = 42; }
}
}
One other method, which is useful under certain circumstances, is to derive the nested class off of the outer class. Like so:
class Outer()
{
protected int outerVar;
class Nested() : Outer
{
//can access outerVar here, without the need for a
// reference variable (or the associated dot notation).
}
}
I have used this technique especially in the context of Structured Unit Tests. (This may not apply to the OP's particular question, but it can be helpful with nested classes in general, as in the case of this "duplicate" question: " Can i access outer class objects in inner class ")
You could pass the enclosing class as a parameter to the nested class constructor, like this:
private NestedClass _nestedClass;
public ParentClass()
{
_nestedClass = new NestedClass(this);
}
Nested classes are generally not recommended and should be private and/or internal. They are, in my opinion, useful sometimes though.
Correct me if I am wrong, you are trying to process the outer control from inner class hence you ran into this. A better way of doing this would be to handle affairs in a event driven fashion. Use an Observer pattern, Register a listener on the outer control (your nested/inner class will be the listener). Makes life simpler. I am afraid that this is not the answer you were expecting!
send the master class as an constructor parameter to the nested (inner) class.
there is a good answer above but I like to write sth.
c# nested class is by default private
private to containing class if your want to use it must be public

Static nested classes in Java

I'm unsure why this code compiles... quoting the Java tutorials:
like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Src: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
public class StaticNested {
private String member;
private static String staticMember;
static class StaticNestedClass {
private void myMethod() {
System.out.println(staticMember);
StaticNested nested = new StaticNested();
System.out.println(nested.member);
}
}
}
I didn't expect to be able to access member directly, but the code compiles fine. Am I misunderstanding the Java spec?
Sorry about the formatting, I'm struggling with my browser + post editor.
You aren't accessing instance members directly.
staticMember is accessing a non-instance member, and nested.member is accessing one through an object reference.
It is correct behavior. What spec meant is that (in your code example) you cant access non-static member field String member directly in static nested class like
public class StaticNested {
private String member;
private static String staticMember;
static class StaticNestedClass {
private void myMethod() {
System.out.println(staticMember);
System.out.println(member);//<-here you will get compilation error
}
}
}
but because non-static fields belongs to object of class you can access it with reference to that object like in your code
StaticNested nested = new StaticNested();
System.out.println(nested.member);
You are accessing it via an instance (not statically).
This does not compile:
System.out.println(member);
Compiler message:
Cannot make a static reference to the non-static field member

jMockit's access to a private class

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

Java: reusable encapsulation with interface, abstract class or inner classes?

I try to encapsulate. Exeption from interface, static inner class working, non-static inner class not working, cannot understand terminology: nested classes, inner classes, nested interfaces, interface-abstract-class -- sounds too Repetitive!
BAD! --- Exception 'illegal type' from interface apparently because values being constants(?!)
static interface userInfo
{
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
MANY WAYS TO DO IT: Interface, static inner class image VS non-static innner class image
import java.io.*;
import java.util.*;
public class listTest{
public interface hello{String word="hello word from Interface!";}
public static class staticTest{
staticTest(){}
private String hejo="hello hallo from Static class with image";
public void printHallooo(){System.out.println(hejo);}
}
public class nonStatic{
nonStatic(){}
public void printNonStatic(){System.out.println("Inside non-static class with an image!");}
}
public static class staticMethodtest{
private static String test="if you see mee, you printed static-class-static-field!";
}
public static void main(String[] args){
//INTERFACE TEST
System.out.println(hello.word);
//INNNER CLASS STATIC TEST
staticTest h=new staticTest();
h.printHallooo();
//INNER CLASS NON-STATIC TEST
nonStatic ns=(new listTest()).new nonStatic();
ns.printNonStatic();
//INNER CLASS STATIC-CLASS STATIC FIELD TEST
System.out.println(staticMethodtest.test);
}
}
OUTPUT
hello word from Interface!
hello hallo from Static class with image
Inside non-static class with an image!
if you see mee, you printed static-class-static-field!
Related
Nesting classes
inner classes?
interfacses
The problem is that you're writing code outside of a method. You do need a class for this and you must put your code inside a method. For example:
static class UserInfo
{
public static void myMethod()
{
File startingFile = new File(".");
String startingPath = "dummy";
try
{
startingPath = startingFile.getCanonicalPath();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This does assume that java.io.File was imported.
You can then call UserInfo.myMethod();
You might also want to import java.util.IOException and catch an IOException instead of a general Exception.
Also, classes and interfaces start with a capital letter by Java conventions.
EDIT: To describe your recent comment on your question:
Use an interface when you want to force similar classes (Think different types of DVD players) to have the same basic functionality (playing dvds, stopping, pausing. You use an abstract class similarly, but when all of the classes will implement some of the same things the same way.
I think you wanted to do this:
static class userInfo
{
public static void something() {
File startingFile=new File(".");
String startingPath="dummy";
try{
startingPath=startingFile.getCanonicalPath();
}catch(Exception e){e.printStackTrace();}
}
}
you cant put code in an interface, an interface only describes how an object will behave. Even when you use Classes, you should put this kind of code in a method, and not directly in the class body.
You can't have actual code in an interface, only method signatures and constants. What are you trying to do?
Looks like you want to write a class here.
You cannot have code in interfaces. Just method signatures.
Top level interfaces cannot be static.
I suggest you start your learning of Java here.

Categories