Inner static classes in java - java

public interface Bsuper {
abstract class A {
abstract void test1();
void test2() {
System.out.print("test2 ");
}
}
}
// second file
public class Bsub extends Bsuper.A {
void test1() {
System.out.print("test1 ");
}
}
// third file
public class Bsubmain {
public static void main(String args[]) {
Bsub sub1 = new Bsub();
Bsuper.A obj = new Bsub();
sub1.test1();
sub1.test2();
obj.test1();
obj.test2();
}
}
It produces the output as expected test1 test2 test1 test2, but my question is in the Bsuper class, class A is static we all know that and now with the abstract keyword it becomes abstract class, but how is it possible to have both abstract and static applied to class at the same time.Is class A really static also or is there any other explanation for it.Please answer!!

how is it possible to have both abstract and static applied to class at the same time.
It is perfectly valid to have a static abstract class. This is different from having a static abstract method, which doesn't make sense, as you can't override such methods, and you're also making it abstract. But with static class, you can of course extend it, no issues. Making it abstract just restricts you with creating an instance of it.
So, even this is valid:
class Main {
static abstract class Demo { }
class ConcreteDemo extends Demo { }
}
In which case, you can't instantiate Demo, and sure you can instantiate ConcreteDemo.

Remember that a static inner class is using a different concept of static.
In this case it means that the inner class does not have access to the outer class's instance variables.
public class Test {
long n = 0;
static class A {
// Not allowed.
long x = n;
}
class B {
// Allowed.
long x = n;
}
}
Making them abstract does not change anything.
abstract static class C {
// Not allowed.
long x = n;
}
abstract class D {
// Allowed.
long x = n;
}

Related

abstract class force instaniation java [duplicate]

This question already has answers here:
Curly braces in "new" expression? (e.g. "new MyClass() { ... }")
(3 answers)
Closed 4 years ago.
we know in java that you cant create an instance of an abstract class.
but, this works:
public abstract class MyAbstract
{
int num = 10;
}
//and in main class
public static void main(String[] args) {
MyAbstract abstractObject = new MyAbstract() {};
System.out.println(abstractObject.num);
}
output:
run:
10
So we can ?
In short what is happening here ?
The syntax
new X(...) { ... }
instantiates an ad-hoc, anonymous class, extending / implementing the class / interface named X.
In your case, the abstract class has all it needs, there are no abstract methods. Therefore, the derived class doesn't need to implement any missing methods.
If you add an abstract method to your abstract class, the example will no longer work. To make it work again, you will have to implement the method in the { ... } section.
public abstract class MyAbstract
{
int num = 10;
abstract void f();
}
public static void main(String[] args) {
MyAbstract abstractObject = new MyAbstract() {
void f() {
...
}
};
System.out.println(abstractObject.num);
}
In addition, you can pass arguments to an extended base class's constructor by using the () part of the syntax:
public abstract class MyAbstract
{
MyAbstract(int argument) {
...
}
int num = 10;
abstract void f();
}
public static void main(String[] args) {
MyAbstract abstractObject = new MyAbstract(5) {
void f() {
...
}
};
System.out.println(abstractObject.num);
}

Q: Abstract class object initiation code?

In this class abstract class object is instantiated by overriding the getNum(), what is the purpose of this?
public abstract class AbstractTest {
public int getNum() {
return 45;
}
public static void main(String[] args) // main function
{
AbstractTest t = new AbstractTest() // From this point didn't understand
{
public int getNum() // function
{
return 22;
}
}; //use of this
System.out.println(t.getNum()); // output
}
}
The instantiation in your main() method is simply an inline class definition of a concrete instance of the abstract class AbstractTest. To be clear, the variable t is an anonymous, non abstract class instance. The following code would achieve the same thing:
public class ConcreteTest extends AbstractTest {
#Override
public int getNum() {
return 22;
}
}
public static void main (String [] args) {
ConcreteTest t = new ConcreteTest();
System.out.println(t.getNum());
}
There are instances in the course of development where it can be cumbersome to have to create a formal class definition. For example, if you only need a single instance of the abstract AbstractTest class, it would be easier to use an inline definition.
We call this 'Anonymous Class': When you need to create and use a class, but do not need to give its name or reused use, you can use an anonymous class. Here is the offical doc. Not only used for abstract class, can also be used for interface and general extensible class.
interface Base {
void print();
}
public static void main(String[] args) {
Base aInterface = new Base() {
#Override
public void print() {
System.out.println("A anonymous implement.");
}
};
Thread aThread = new Thread() {
#Override
public void run() {
super.run();
}
};
}

when you extend a private class. are the public and protected members of class become private

when you extend a private class. Are the public and protected members of class become private. if not any explanation.
if you extend a nested private class, it wont change public/protected modifiers of the members. Here is an example :
public class Clazz {
private static class NestedClazz {
public int value = 123;
}
public static class NestedClazzExt extends NestedClazz {
}
}
you can now access the inherited member: value from outside
public static void main(String[] args) {
NestedClazzExt nestedClazz = new Clazz.NestedClazzExt();
System.out.println(nestedClazz.value);
}
you can create private class in side a class . We call it as Nested classe. Means a class inside a class. The Concept itself is saying that you can create private class in side another class. The private class will act like as data member to the outer class.
So, You can't extend the private class.
Based on your query I tried to prepare a simple class.
public class pvtClass {
private class As {
public String abc = "private attribute";
public void print(){
System.out.println("privateClass");
}
}
class Ab extends As{
public String ab = "extended attribute";
public void printAb(){
System.out.println("extended class");
print();
System.out.println(abc);
}
}
public static void main(String as[]){
Ab ab1 = (new pvtClass()).new Ab();
As as1 = (new pvtClass()).new As();
ab1.printAb();
as1.print();
System.out.println(as1.abc);
}
}
If you have a look at this class, I have a private class named "As" which has public attribute and public methods. I have another class named "Ab" which extends "As". I have written a main method to invoke the private attribute and methods.
below is the output for the code snippet:
extended class
privateClass
private attribute
privateClass
private attribute
There is a difference between the access of the members of a class and the access to the type itself.
public class C {
private class InnerP1 {
public void m() {
System.out.println("InnerP1.m()");
}
}
private class InnerP2 extends InnerP1 {
public void p() {
this.m();
System.out.println("InnerP2.p()");
}
}
public InnerP1 strange() {
return new InnerP2();
}
}
In this example, the interface I is visible from outside class C. The classes InnerP1 and InnerP2 are not visible from outside C. Jave itself makes not restrictions to the visibility of types you use in your public interface. The method strange() of class C returns a result of class InnerP1. Since outside of C we do not know anything about the class InnerP1 other than it is subtype of Object, the only thing we can do is use the result of strange() as an Object.
public class D {
public static void main(String[] args) {
C c = new C();
Object o = c.strange();
if(o.equals(c.strange())) {
System.out.println("Strange things are going on here!");
}
}
}
As #KnusperPudding pointed out already, the visiblity of public members is not changed, we might just not have enough knowledge of the type itself to access them.
Access to members cannot be restricted by sub-classing. When you mark a class as private then access via the class name is restricted i.e. to the same .java file, however once you have an instance of this class it can be accessed at least as easily as the super class.

get caller class name from inherited static method

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());
}
}

Java: Parent Methods accessing Subclasses' static variables?

I am trying to understand my way around polymorphism in Java. I created a parent class that has too many common methods that all children will use in the same manner.
Each of the subclasses' children all share static information, These variables or information will be used in the methods declared only in the parent.
The problem wish accessing static variables from Parent methods seems not really possible,
Its a solution to declare the common information per instance but since there will be 1000s of instances its such a waste of memory.
A simple elaboration of what i mean is the following code :
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
static
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
static
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
the output i expect was
1
2
1.
but what happens is :
1
2
2
One might think that on the initiation of each subclass the static variables of this subclass is set and then all methods referring to this subclass has access to the corresponding 'k' value.
But what actually happens is that all subclasses edit in the same static variable that is shared along all subclasses and hence destroys my whole point of using static variables for each subclass and its instances and using commmon methods in the Parent accessing these variables.
Any idea how can this be done ?
An option is to access the subclasses' static data through an abstract (non-static) method:
abstract public class Parent {
protected abstract int getK();
public void print() {
System.out.println(getK());
}
}
public class Child1 extends Parent {
private static final int CHILD1_K = 1;
protected int getK() { return CHILD1_K; }
}
public class Child2 extends Parent {
private static final int CHILD2_K = 2;
protected int getK() { return CHILD2_K; }
}
When you make new testChild2().print(); the static block on testChield2 was executed and change the value to 2.
static blocks only execute once when loaded by the ClassLoader.
This one give the output you want:
class testParent {
static int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
testChild2.k =2;
}
}
public class testChild1 extends testParent{
{
testChild1.k = 1;
}
public static void main(String[] args)
{
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Non static code blocks execute everytime the class is instanciated.
Premature optimization is the root of all evil. I don't think you'll run into any memory issues with thousands of instances, each with their own data, unless you're working on a tiny embedded system of some kind. Static variables are not intended to do what you're trying to do with them.
Static variables are specific to the class itself. If you want the same field in different instances of a class to have different values, then that field cannot be static.
The solution: don't make k static.
class testParent {
int k;
public void print()
{
System.out.println(k);
}
}
class testChild2 extends testParent
{
{
this.k =2;
}
}
class testChild1 extends testParent{
{
this.k = 1;
}
public static void main(String[] args){
new testChild1().print();
new testChild2().print();
new testChild1().print();
}
}
Demo
(ignore the static class business - that's just to make it work in ideone).

Categories