I have some classes nested one in another
public abstract class I
{
public abstract int f();
}
public class J
{
private List<I> li;
public J(List<I> l)
{
li = l;
}
}
public class A // first class
{
private int x; // field of A
public class B extends J // second class
{
public B()
{
super(new ArrayList<I>() // super call
{{ // array initializer
add(new I() // third class
{
#Override
public int f()
{
return x; // <- here!!!
}
});
}});
}
}
}
Under these conditions, I get the error: "error: no enclosing instance of type A is in scope". Removing any element from this setup fixes this error. Also, taking x and saving it to another variable then using that variable also works.
What is happening here? It seems like a bug in a compiler for me.
It is not allowed to have 2 public classes in one Java File and file name should be same as public class name.
To experiment with your code I made a new Test class like this. I see no errors reported (using Java 8). Perhaps this is a build issue.
public class Test {
public abstract class I {
public abstract int f();
}
public class J {
private List<I> li;
public J(List<I> l) {
li = l;
}
}
public class A // first class
{
private int x; // field of A
public class B extends J // second class
{
public B() {
super(new ArrayList<I>() // super call
{
{ // array initializer
add(new I() // third class
{
#Override
public int f() {
return x; // <- here!!!
}
});
}
});
}
}
}
public void test() {
System.out.println("Hello");
}
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc="test">
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
//</editor-fold>
}
}
Java 7 also seems to accept this code.
Related
In the below code, in class_1 and class_2 both extends from AbstractClass. I am trying when I call:
c1.setValid(5)
The following two lines, returns 5 as well:
System.out.println(c1.getValid());
System.out.println(c2.getValid());
pleas let me know how can I modify the Super class to achieve that.
main:
public class Main {
public static void main (String[] args) {
Class_1 c1 = new Class_1();
Class_2 c2 = new Class_2();
System.out.println(c1.getValid());
System.out.println(c2.getValid());
c1.setValid(5);
System.out.println(c1.getValid());
System.out.println(c2.getValid());
}
}
class_1
public class Class_1 extends AbstractClass {
public Class_1() {
// TODO Auto-generated constructor stub
}
public void setValid(int v) {
SetValid(v);
}
public int getValid() {
return GetValid();
}
}
class_2.:
public class Class_2 extends AbstractClass {
public Class_2() {
// TODO Auto-generated constructor stub
}
public void setValid(int v) {
SetValid(v);
}
public int getValid() {
return GetValid();
}
}
code:
public abstract class AbstractClass {
public int isValid = -1;
public void SetValid(int value) {
this.isValid = value;
}
public int GetValid() {
return this.isValid;
}
You can delete setValid and getValid from Class 1 and 2
and use the parent's function SetValid and GetValid
If that is your question.
If your goal is to have all instances of your class to always have the same value, then you can simply use the static keyword.
public abstract class AbstractClass {
public static int isValid = -1;
...
}
When static is used for a global variable, you're essentially declaring that this global variable will be shared by every instance of this class, including it's children.
Therefore, updating isValid with a new value in Class_1 will cause Class_2 to have the same value that Class_1 updated.
I also done this example creating object for both class and call the method is there anyway to override the baseclass?
class Car {
void Max() {
System.out.println("Audi");
}
}
class Speed extends Car {
void Max() {
System.out.println("300");
}
public static void main(String args[]) {
Speed s=new Speed();
s.Max();
}
}
At the risk of being called a "give me the repz" type person...hopefully this helps:
This first class is a BaseClass, you can create a new one by writing:
BaseClass myBaseClass = new BaseClass();
public class BaseClass {
private int aNumber; //This global variable is private and so cannot be overwritten.
int anotherNumber; //This global variable is package scope and so can be accessed by sub-classes in the same package.
protected yetAnotherNumber; //This variable is accessible by any subclasses.
public int numberAvailableToEveryone; //This global variable is accessible to anyone and everyone.
public BaseClass() {} //This is a constructor (no return type)
private void myPrivateMethod() {} //This method cannot be overwritten
void packageScopeMethod() {}
protected void thisMethodCanBeOverwrittenBySubClasses() {}
public void theWorldCanCallMe() {} //extendable to the world, not much different than protected scope tbh
}
Now, to overwrite a method you can create an anonymous class like so:
BaseClass myAnonymousClass = new BaseClass() {
public void theWorldCanCallMe() {
//in here you can override the method to do whatever you want.
}
}
or you could define a subclass like so:
public class SubClass extends BaseClass {
#Override
public void tehWorldCanCallMe() {
//again your new code goes here
}
}
and then instantiate it like so:
SubClass myClassThatOverridesAMethod = new SubClass();
A car example closer to your code:
class Car {
private String name;
int speed = 100;
Car(String name) { //This is the base classes constructor
this.name = name;
}
String max() {
return speed;
}
void run() {
System.out.println(name);
System.out.println(max()); //will print the base speed unless overridden
}
}
class Audi extends Car {
Audi() {
super("Audi")
}
}
class Speed extends Car {
Speed() {
super("Speed");
}
#Override
String max() {
speed = 300;
return speed;
}
public static void main(String args[]) {
Speed s=new Speed();
s.run();
}
}
i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));
In my program, I want to be able to access certain methods based on the constructor I initialize and nothing else. For example:
public class A {
int paramOne;
float paramTwo;
public A(int paramOne) {
// Constructor One
}
public A(float paramTwo) {
// Constructor Two
}
public void ConstructorOneMethodOnly(int paramOne) {
// Only used when Constructor One is initialized
}
public void ConstructorTwoMethodOnly(float paramTwo) {
// Only used when Constructor Two is initialized
}
}
In the code given, is there a way of achieving what I have described in the comments and in my question? If so, can you describe how to do so?
As per Sotirios Delimanolis' comment, you can not restrict the accessibility of a method based on the constructor used.
I think this logic should be divided into two class, that is the more clear implementation I can find out.
public class IntDemo {
int paramOne;
public IntDemo (int paramOne) {
...
}
public void ConstructorOneMethodOnly(int paramOne) {
...
}
}
class FloatDemo {
float paramTwo;
public FloatDemo(float paramTwo) {
...
}
public void ConstructorTwoMethodOnly(float paramTwo) {
...
}
}
public class A {
int paramOne;
float paramTwo;
int constr = 0;
public A(int paramOne) {
// Constructor One
constr = 1;
}
public A(float paramTwo) {
// Constructor Two
constr = 2;
}
}
and check constr variable before invoking methods.
Im not sure if this directly helps you but it may help you and more.
I suggest using a generic class like this.
public class A<T> {
public A(final T t) {
}
public void method(final T t) {
}
}
If you dont know how to use a generic class here is an exmaple
final A<Integer> aInteger = new A<Integer>(1);
final A<Float> aFloat = new A<Float>(5.4f);
Hope this helped!
I have the following scenario :
public class A {
private int x = 5;
public void print()
{
System.out.println(x);
}
}
public class B extends A {
private int x = 10;
/*public void print()
{
System.out.println(x);
}*/
public static void main(String[] args) {
B b = new B();
b.print();
}
}
On executing the code, the output is : 5.
How to access the child class(B's) variable(x) via the parent class method?
Could this be done without overriding the print() method (i.e. uncommenting it in B)?
[This is important because on overriding we will have to rewrite the whole code for the print() method again]
EDITED
More Clarification :-
The motive of the question is to use the value of a child class private variable from its parent class method. This doesn't require changing the value of the parent class private variable in order to achieve the desired result.
The answers posted here, though, led me to my desired answer, which I have posted below.
(Thanks all for your time and help )
class A {
private int x = 5;
protected int getX() {
return x;
}
protected void setX(int x) {
this.x = x;
}
public void print() {
// getX() is used such that
// subclass overriding getX() can be reflected in print();
System.out.println(getX());
}
}
class B extends A {
public B() {
// setX(10); // perhaps set the X to 10 in constructor or in main
}
public static void main(String[] args) {
B b = new B();
b.setX(10);
b.print();
}
}
EDITED
Below is a general answer using abstract class and method to solve similar scenario:
abstract class SuperA {
protected abstract Object getObj();
public void print() {
System.out.println(getObj());
}
}
class A extends SuperA {
#Override
protected Object getObj() {
// Your implementation
return null; // return what you want
}
}
class B extends A {
#Override
protected Object getObj() {
// Your implementation
return null; // return what you want
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
After reading all the answers posted here, I got what I was looking for. The following is what I feel is the best answer for my question :
public class A {
private int x = 5;
protected int getX(){
return x;
}
public void print(){
System.out.println(getX());
}
}
public class B extends A {
private int x = 10;
protected int getX(){
return x;
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
Setting up a protected getter and overriding it is better than overriding the print() method itself, as there could be any other huge method in place of the print method which might need to access the value of the child class variable(s).
To solve your question you have to define the fields in the parent class A like protected (so it will be inherited on the child class) and set the field value x inside the constructor in the child class B. The print method is also inherited from A class so you can invoke it directly from parent class.
I hope this can help you.
public class A
{
// fields declaration
protected int x = 5;
public void print()
{
System.out.println(x);
}
}
public class B extends A
{
public B()
{
// set child x value. The field have been defined in the parent class
x = 10;
}
public static void main(String[] args)
{
A a = new A();
a.print(); // print 5
B b = new B();
b.print(); // print 10
}
}
You can always add it to the constructor:
public class B extends A {
//this line is unnecessary: private int x = 10;
/*public void print()
{
System.out.println(x);
}*/
public B()
{
x=10;
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}
The reason it won't work as you try it is that default values only get evaluated once. So when it's default 5 in A, it stays 5 even though you used default 10 in B.
You should expose a getter for the value you want and override that in the child class.
Like so:
public class A {
private int x = 5;
public void print()
{
System.out.println(getX());
}
protected void setX(int x)
{
this.x = x;
}
protected int getX()
{
return x;
}
}
public class B extends A {
/*public void print()
{
System.out.println(x);
}*/
public B()
{
setX(10);
}
public static void main(String[] args) {
B b = new B();
b.print();
}
}