I have a question about Java.
I have a class Say.java that has some methods, like sayHello(), saySomething(), sayBye(), ...
I have other classes too. I have a class Person, and two subclasses of Person: Senior and Junior.
My job to do is the following:
I have to set the Say.java class to be private, and create a public class SayFactory.java, with a method called getInstance. Then, to create a new instance of the Say.java class, I have to call my getInstance method with one argument: an instance of either Senior.java or Junior.java. If I create an instance of Say.java using a Senior.java object, I must be able to access all of the methods of Say.java. But if I do the same thing with Junior.java, I should be able to access all of Say.java's methods EXCEPT saySomething().
Can someone please explain how to do this and how it works?
Apologies by the way - I'm from Spain so my English isn't that great. If you don't understand the question, let me know and I'll try to write it out more clearly.
First refer to this as answer to making a class private: Java: Why can we define a top level class as private?
For the objects that you want "private" you will have to make all the fields and possibly methods of it private (depending on what you need). Then as #user1071777 mentioned set up public getters and setters.
Some basic information on calling methods of an object:
http://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
To create the connection between classes you can have a class have another class as part of its definition and set it up through constructor or public setter.
I know that I can't write Private Class but I can do a inner class.
I have a class SayFactory and within this I got another called Say
The SayFactory have a method called getInstance(), and in this method I create an object of Say class and return this object. The problem is, how to deny access to method saySomething() if the parameter of getInstance() is a object of Junior.
Related
I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project.
I notice that when I call getInstance() (the method from the singleton's interface) from the POJO, there is an error occuring, telling me that the method has to be static, but if I make the method static, then I have to write the implementation in the interface and I can't get the singleton instance.
Your current approach with the interface is flawed. By default, all methods in an interface (up until Java 8) are static, and are implemented by instance methods in the implementing class.
This means, this is not an option. After all, you'll need to run the method to create an instance, meaning, you don't have an instance yet, so you have no instance to call it on.
Putting the same static method in an abstract class you extend, is also not a solution: a super class should never be aware of it's subclasses. If it is a static method (which it needs to be), you need to keep it in the class itself: a static method in an abstract class can (through an anonymous implementation of the abstract class) return an instance of the abstract class, but this is not the same as an instance of the subclass, which is what you are looking for.
In order to use this method for the subclass, you will need to inherit it from the super class. But, it will still return an instance of the super class. You'll need to overwrite the method in the subclass by the correct one, so the best solution is to add it straight in your Singleton class.
You are not allowed to have static methods in your interfaces (at least not until Java 8). Something like this is not allowed:
MyInterface var = new MyImplementingClass();
var.staticMethod();
Just remove the interface and do your static method call against the class where the static method resides.
Search a bit for the singleton pattern - the 'standard' way to do this involves classes and not interfaces, so rethink your design.
The idea seems to be wrong. A static method is always at a class level and hence you can never declare a method as static in a Java interface(you can do this in Java 8). However, this seems like the wrong design. If you really want to do something like this -
1)Make the Interface an abstract class.
2)Create a static method called getInstance();
3)Extend the abstract class in your POJO singleton class.
Hope this helps!!
Given, for example, a class like this:
public abstract class AbstractSomething {
public static volatile SingularAttribute<Somefield, AnotherField> myAttribute;
}
how can I get an instance of myAttribute via reflection. There are no implementing classes for AbstractSomething.
EDIT
No, we need an instance of the SingularAttribute<T, S>. And the reason we need to use reflection is becuase these classes are generated and passed into our method as a Class object. We have no way no know which AbstractSomething we are receiving. There are quite a few of them.
EDIT 2
Found out what the issue was. When a Hibernate context is present in the application, the interfaces on the abstract class are replaced with their implementation counterparts when accessing them.
No big deal actually, you can do something like this:
Field field = AbstractSomething.class.getField("myAttribute")
And then you can access it by invoking field.get(null) and field.set(null, value)
The real question is WHY do you want to use reflection, but I guess you have your reasons.
EDIT:
If you have a Class instance in before hand (lets call it classInstance) then you can do
Field field = classInstance.getField("myAttribute")
to get the Field that reificates the field you are looking for... and if you want all fields just invoke the getFields method.
You don't really need a concrete implementation nor an instance of the reificated class in question in order to access the static fields.
No need for reflection. The field belongs to the class, and no matter how many subclasses there are, there is only one instance of the AbstractSomething class, so just:
SingularAttribute<Somefield, AnotherField> attr = AbstractSomething.myAttribute;
I'm reviewing some Java code written long ago and not being a Java developer, I have a question. I found the following lines in the body of a class. Someone is creating an instance of SearchQueryParameter however there are curly braces following "new SearchQueryParameter" and it appears that someone overrode some functions here.
My questions are the following.
1) Are these functions overwritten at an instance level?
2) Does this language feature have a name?
public static final SearchQueryParameter X_POSTDOC_WORKFLOW_STEP = new SearchQueryParameter(128,"XPOSTDOCWorkflowStep",AdvancedFields.X_EVENT_POSTDOC_WFSTEP,SearchTypes.XEVENT_DOCUMENTS) {
#Override
protected int getFilterType() {
return SEARCH_FILTER;
}
<<snip>>
};
Thanks, mj
Background:
This is called anonymous class. It is a class that extends a non final class or implements a single interface and you're creating a single instance of this class.
Now, to your questions:
1) Are these functions overwritten at an instance level?
No, they are at level class. You have a new subclass of the desired class and this subclass overrides the method. Then, you create a new instance of the subclass.
2) Does this language feature have a name?
Yes, it is anonymous class.
You probably should have done some research on your own first, but that is called an anonymous inner class.
The code creates an instance of an anonymous class (SearchQueryParameter) and then overrides one method in it.
Essentially, it creates something that extends the SearchQueryParameter class and which overrides the getFilterType() method.
Since only one instance of this particular class definition can ever be created (without reflection), the function may appear like it's being overridden at an instance level but is actually getting overridden at the class level (since it may replace the existing definition).
It's called an anonymous class.
I am new to programming and was studying "Head First Java", I just saw a problem where there was used Math class like this
int x= Math.round(float value);
and it was mentioned we don't need to instantiate Math class because its constructor is set private. What does that mean? Until now I read we need to instantiate that class and reference variable to play around with methods and instance variables of the class how does Math class work like this?
we don't need to instantiate Math class because its Constructor is set Private
Because all the methods in Math class are static you can use the class name to invoke them. So there is no use instantiating the class , hence the constructor was declared private. it will also prevent sub classing the Math class, since it is the only constructor.
Look at the open source code :
Don't let anyone instantiate this class.
private Math() {} // only constructor defined in Math class
The methods of Math class doesn't depend on the internal state of the class , they are just like utility functions . So it was wise to declare them as static. static methods can be invoked by directly using the classname , hence no use of instantiating the class. They belong to the class, not specific objects of that class.
You can refer the JLS 8.4.3.2 :
A class method is always invoked without reference to a particular object.
The Math class have all methods as a static, and you need to get the method from the class itself. No need to create instance variable to access Static variable and methods
Refer Math Class java doc. you find all method here static i,e. Math.round
Private constructors means that they can only be called upon from within the class to which they belong, a good example of the use of private constructors can be found here Can a constructor in Java be private?
Private constructors do however have nothing to do with the fact that you can use methods from the MATH class without instantiating them. This is because the methods of MATH class are static i.e. a static method can be called upon without instantiating an object of the class to which the methods belong.
As said in the comments above, you have no use of instantiating a MATH object, therefore the constructor is private, but you could use the MATH methods anyway had the constructor been public.
It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it Class objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different Class argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, e.g.:
new className(optional argument list){classBody}
new interfaceName(){classBody}
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a Class object for an anonymous class?
Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
foo((new Object() { ... }).getClass());
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
EDIT
Your question also says that you want to call foo "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class definition, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that foo will create using the Class object passed to it will not have them captured.
short answer
you cannot (using only JDK classes)
long answer
give it a try:
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
#Override
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
let's creating two new class "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
however you cannot instantiate this classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for every anonymous class.
However you can build dynamic classes at runtime using bytecode manipulation libraries such ASM. Another approach is using dynamic proxies, but this approach as the drawback that you can proxy only interface methods (so you need a Java interface).
You can only reference an anonymous class ONCE. If you do not instantiate it there, you cannot instantiate it since you do not have a name for it.
Hence I believe that anonymous classes can only be used in conjunction with a "new BaseClass()".
In your situation you would pass a BaseClass object to your method doing the work, and instantiate the anonymous object in the source code when you need the object to pass.
You can't access the Class object of an anonymous class without instatiating it. However, if you only need access to the class, you could define local classes within your method and refer to these using the ClassName.class literal syntax.
You can assume the name of an anonymous class and call Class.forName("mypackage.MyBaseClass$1") to get a handle to an anonymous class. This will give you the first anonymous class defined in your MyBaseClass, so this is a rather fragile way to refer to a class.
I suspect whatever you are trying to do could be done a better way. What are you really trying to achieve? Perhaps we can suggest a way which doesn't require you to pass a Class this way.
You can access the class object of an anonymous class by calling .getClass() on it immediately after creation. But what good would that do?
I think the key is in this part of what you said:
I'm working with a library method that requires that I pass it Class
objects.
Why does it want you to pass it Class objects? What does this library do with the Class objects you pass it? Instantiate objects? But if so, what constructor does it use and how does it decide what arguments to pass? I don't know what library you are using or what it does, but I would guess that it always creates objects using the no-argument constructor. However, that will not work for anonymous classes anyway, since they have no public constructor (and in any case, to instantiate any non-static inner class, a reference to the outer instance must be provided, so there is no no-argument constructor).