I discovered that following code compiles:
class Ideone
{
public static void main (String[] args){
new Ideone().m();
}
final private void m(){
System.out.println("private final method");
}
class A extends Ideone{
public void method(String [] args){
m();
}
}
}
and executes.
I am very wondering about this.
Can you explain why does java designers(founders) made that it works?
A final method can be inherited by a sub class regardless the sub class is outside the parent class or inside the parent class. But you cannot override the final method in your subclass. If the final method is private you cannot inherit that in your subclass unless your subclass is inside the parent class (like in your example).
Since you declare the method private, then final has no effect and is redundant.
Overriding a private method don't really make much sense.
It is no different then calling a private method in a class from another method in the same class (which might be public). That is something that is done often to keep code more readable and method's manageable in size.
I don't think it is a stupid question :)
Take the Builder-pattern for example. It utilizes private constructors to make sure the class is constructed the correct way. So understanding what you have available in different scope's, and why is important :)
class Ideone {
private String m;
private Ideone(String m) {
System.out.println("Build me with: " + m);
this.m = m;
}
public String getM() {
return m;
}
static class IdeoneBuilder{
String m;
public IdeoneBuilder withM(String m) {
this.m = m;
return this;
}
public Ideone build() {
return new Ideone(this.m);
}
}
public static void main (String[] args){
// new Ideone(); // will not compile
Ideone ideone = new IdeoneBuilder()
.withM("test").build();
}
}
Edit: You can make the class Ideone final, and it will still work. And you are also making it impossible to subclass it. In other words, you make sure there is no other way to construct an object of your class other than using the builder (unless the use of reflection).
Related
How to stop other classes to create the object of the class using new operator in java. For Example, i have one class A. i don't want any other class to create its object using new operator.
One Approach is that i can throw IllegalArgumentException in the constructor of class A.
is there any other?
public class A{
public A(){
throw IllegalArguementException();
}
}
The approach what you followed is wrong.. you can't create object of your class as well with this approach.
So you must make your construction private and write static method to get the instance of the class.
class Test
{
private Test(){ }
public static Test getTestInstance(){
return new Test();
}
}
Hope it helps,
You can do it by making the constructor private.
class A
{
int i;
private A()
{
i=1;
}
public static A getInstance()
{
return new A();
}
}
class B
{
A a;
public B()
{
/* a=new A(); //This doesn't compile */
}
}
Implementing Singleton in Java 5 or above version using Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.
public enum SingletonEnum {
INSTANCE;
public void doYourStuff(){
System.out.println("Singleton using Enum");
}
}
And this can be called from clients :
public static void main(String[] args) {
SingletonEnum.INSTANCE.doYourStuff();
}
You can make the class abstract (though in this case no instance of this class can be instantiated by any class, so perhaps it's not what you want), or make the constructor private.
private A() {}
Make the constructor private.
I have following classes (note that methods are static):
class Base
{
public static void whosYourDaddy()
{
Class callerClass = // what should I write here to get caller class?
System.out.print(callerClass.getName());
}
}
Class A extends Base
{
public static void foo()
{
A.whosYourDaddy();
}
}
Class B extends Base
{
public static void bar()
{
B.whosYourDaddy();
}
}
And when I call:
A.foo();
B.bar();
I'd like to get output:
AB instead of BaseBase. Is it even possible with static methods (in Java 7)?
What you can do, but shouldn't :) is use the Throwable getStackTrace method. Aside from the smell, this is pretty slow, because getting the stack trace isn't that fast. But you will get an array of StackTraceElement, and each one will contain the class of teh class that is calling it (and you can also get the file and line, and if you separate the two with a : you can get a clickable link in eclipse, not that I'd ever do such a thing...).
Something like
String className = new Throwable().getStackTrace()[1].getClassName();
Hope that helps :)
private static class Reflection {
private static final SecurityManager INSTANCE = new SecurityManager();
static Class getCallClass() {
return INSTANCE.getCallClass(2);
}
private Reflection() {
}
private static class SecurityManager extends java.lang.SecurityManager {
public Class getCallClass(int i) {
Class[] classContext = getClassContext();
if (i >= 0 && i + 1 < classContext.length) {
return classContext[i + 1];
}
return null;
}
};
}
Is it even possible with static methods (in Java 7)?
No, Static methods aren't inherited. Only non-static methods are inherited.
In your case change Base (and subclasses) as follows:
class Base
{
public void whosYourDaddy()
{
Class<?> callerClass = getClass();
System.out.print(callerClass.getName());
}
}
I want to make a convenient super class that will make an instance of whatever subclass it is ran from, without having to hard-code the name of the sub class. What is the fastest way to do this?
We can assume that the subclasses' constructors will have same signature, e.g. no parameters.
class Main {
public static void main (String [] args) {
Main m = new NAME-OF-SUBCLASS();
}
}
class MainSub1 extends Main { /*...*/ }
class MainSub2 extends Main { /*...*/ }
So when invoking main from MainSub1 ($ java MainSub1 from the command line), a MainSub1 object is created, etc.
As I wrote this, i found this thread where the accepted answer says it can't be done, but of course it can, somehow, through reflection or something, right?
Not that I'd really recommend it, but there's a dirty trick to it:
class Main {
static Main m;
public static void main (String [] args) {
// use m
}
}
class MainSub1 extends Main { static { m = new MainSub1(); } }
class MainSub2 extends Main { static { m = new MainSub2(); } }
A serious answer would be to write a separate main for each subclass, but let it call a common inherited method that accepts an appropriate instance.
If we have class A & B, and class A's constructor is private, and we want to use an instance of A in B, how to do that ? I see an answer that says "provide a static method or variable that allows access to an instance created from within the class " but I didn't understand that.
The code pattern you seek is called the Factory Method.
The class provides a static method that returns an instance of its own class. Private constructors are visible to all methods (including static ones) of the class, so the static method can invoke the private constructor on the caller's behalf.
Here's an example of this pattern in action:
public class A {
private A() {
}
public static A create() {
return new A();
}
}
This is often employed in conjunction with the Singleton Pattern, which would change the above example to this:
public class A {
private static A INSTANCE = new A();
private A() {
}
public static A getInstance() {
return INSTANCE;
}
}
A needs to have a public method that provides an instance of the class A, eg:
class A {
/*Constructors and other methods omitted*/
public static A getInstance() {
return new A();
}
}
Alternatively, if B is an inner class of A (or vice-versa), then B can directly reference the constructor eg:
public class A {
private A() {}
public static class B {
private A instanceOfA = new A();
public B() {}
}
}
A class that only has private constructors is designed so that other classes cannot instantiate it directly. Presumably there is a sound reason for this. The class may provide a factory method for instantiating the class ... or getting an existing instance of the class.
If you need to change the design, the best way is to modify the class; e.g. by making a constructor visible, or by adding a factory method. If you can't do that, I think it is possible to use reflection to break the visibility rules and create an instance using a private constructor. However, I'd only do this as a last resort ... and not before carefully analysing the consequences for the overall application.
Private constructors are intended to make a class not to have any instance. But the content can be accessed from child class using super(). Implementation is like this:
public class ClassA {
private int val;
private ClassA(int val)
{
this.val = val;
}
public int getVal() {
return val;
}
}
public class ClassB extends ClassA {
public ClassB(int val) {
super(val); } }
...
ClassB b = new ClassB(4);
System.out.println("value of b: " + b.getVal());
As an example see class Calendar. To get an instance you must not call its constructor but use a static method:
Calendar rightNow = Calendar.getInstance();
source
Suppose I have a class with several static void methods, for example:
class MyClass {
public static void doJob() {
// ...
}
public static void doSmthElse() {
// ...
}
}
how can I modify it to call my static methods like this:
MyClass.doJob().doSmthElse().doJob();
instead of
MyClass.doJob();
MyClass.doSmthElse();
MyClass.doJob();
I know how to do it with non-static methods (just return this), but how to do it with static fields?
Well, you could do this:
// Horrible, don't do it!
class MyClass {
public static MyClass doJob() {
// ...
return null;
}
public static MyClass doSmthElse() {
// ...
return null;
}
}
At that point your code will compile, as Java allows access to static methods "via" references. The fact that you're returning null is irrelevant, because the compiler will only look at the compile-time type of the expression MyClass.doJob() in order to work out which doSmthElse() method to call; the static method will then be called without examining the return value at all.
But please don't do this - it's a really nasty code smell, as your code looks like it's doing one thing when it's actually doing another.
Options:
Just live with your more verbose calls
Extract the static methods into a class where it makes sense for them to be instance methods (this may well improve testability etc as well)
Import the methods statically
Create a larger method in MyClass which calls the three methods one after another.
You can make this class singleton and do
return getInstance();
in every method
You can create a dummy instance of you class and return this. You will use static members of class, but return a reference to regular instance (just for fun, just for code style). But I wouldn't like to use this approach.
class MyClass {
private static int data = 0;
private static MyClass link = null;
public static void doJob() {
// do job with static data such as "data"
return checkMe();
}
public static void doSmthElse() {
// do someting else with static data such as "data"
return checkMe();
}
private MyClass static void checkMe() {
if (link == null) link = new MyClass();
return link;
}
}
It is immpossible because there is no object you can return.