public class AreaDeRectangulo extends JFrame {
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public JLabel AltoL, AnchoL, AreaL, PerimetroL;
public JTextField AltoTF, AnchoTF, AreaTF, PerimetroTF;
public JButton Calcular, Salir;
public BotonDeCalcular cbHandler;
public BotonDeSalir ebHandler;
}
public class BotonDeCalcular implements ActionListener {
public void actionPerformed(ActionEvent e) {
double alto, ancho, area;
ancho = Double.parseDouble(AnchoTF.getText());
alto = Double.parseDouble(AltoTF.getText());
area = ancho * alto;
AreaTF.setText(" " + area);
}
}
public static class BotonDeSalir implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
public static void main(String[] args) {
AreaDeRectangulo rectObj = new AreaDeRectangulo();
}
}
}
Why the classes "BotondeCalcular" and "BotondeSalir" have to be created inside the main class? are they like a mini-classes?
PD: it gives me an error if I try to separate the classes
They are called Nested Classes (some call them Inner Classes or other names)
As for why the author chose to do so, the java docs provide some suggestions.
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.
These are design decisions that developers make. There is no hard reason why a class must be defined inside another class.
This is because they are inner classes and use the features available to inner classes. Let's look at BotonDeCalcular:
ancho = Double.parseDouble(AnchoTF.getText());
This uses a field called AnchoTF, declared in the outer class. In essence, that line is equivalent to the more verbose:
ancho = Double.parseDouble(AreaDeRectangulo.this.AnchoTF.getText());
If you want to move those classes to separate files, you'll need to hold an instance of AreaDeRectangulo that you pass in by constructor.
Related
I was going through the legacy code base and observed that so many places they are using the public static class inside an outer class and nested public static class is not just being used in the outer class but its being used in so many other class?
What would be the design decision behind that and if it being used outside as well then why it wasn't created as a standalone public class in the first place itself.
So in my example it looks like below :-
public class OuterNestedClass {
private int a;
private List<InnerClass> innerClasses;
public static class InnerClass {
private int b;
public InnerClass(int b) {
this.b = b;
}
public void show(){
System.out.println("Value of b "+b);
}
}
}
And other class which uses the innerclass looks like below :-
public class OutsideClass {
public static void main(String[] args) {
OuterNestedClass.InnerClass innerClass = new OuterNestedClass.InnerClass(10);
innerClass.show();
}
}
Let me know if any clarification is required.
Main reason for that would be namespacing. Static classes are utility classes, and those tend to grow very large. Nested classes let you break your utilities nicely, while still keeping everything together.
So, instead of having Utils with 20 methods, you probably have Utils.Password with 5 and Utils.Json with 15
Best example for that I've seen is how Retrofit.Builder is done:
https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Retrofit.java#L394
There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data. My program is very lengthy ,I just want the logic of this.Thanking you in advance.
Class A.java
public class A
{
public static void main(String ar[])
{
int a=100;
}
}
Class B.java
public class B extends A
{
public static void main(String m[])
{
A obj=new A();
System.out.println("Variable of class A is :"+ obj.a);
}
}
I have done this thing to get access like i declared variable a as Static so that i can directly get access but it's not working. and when i am compiling B.java It giving me error
cannot find symbol at := System.out.println("Variable of class A is :"+ obj.a);
And
Illegal start of expression (when i am delaring variable a as public)
:-(error)public int a=100; [in class A].
Why are you using the static main method? Besides that the field a is local and not accessible outside the scope. Use this instead.
public class A
{
public int a;
public A()
{
a=100;
}
}
You don't have two true object-oriented classes above, but rather little more than two receptacles for static main methods. To combine code from two classes well, you will want to scrap that code and make OOP-compliant classes, complete with instance fields and methods. For more on this, check out the OOP section of the Java tutorials: link to OOP tutorial.
First, get rid of main() in A. You only want one main() in your application, and it's in B (since the one in A doesn't actually do anything):
public class A {
}
Now, you want A to have a class-level int value:
public class A {
private int a;
}
And you want it to have a default value of 100, yes? A constructor is a good place to do that:
public class A {
private int a;
public A() {
this.a = 100;
}
}
Now any time you do this:
A obj = new A();
you will have an object with a value. In order to access that value from outside that object, you need a "getter":
public class A {
private int a;
public A() {
this.a = 100;
}
public int get_a() {
return this.a;
}
}
Now in B (or anywhere, really), you can create an instance of A and access that value by using the "getter":
A obj=new A();
System.out.println("Variable of class A is :"+ obj.get_a());
Semantically, don't think of it as "accessing a variable from another class". Instead, think of what your objects are and what they represent. If it were a physical, real-world object which internally contained some kind of value.
When you create an instance of that object, the instance would internally have that value somewhere. From the outside of that object, it doesn't really matter how that value is internally maintained. There just needs to be some kind of interface to see the value. Which is what the "getter" method does.
One-liner answer: To access a variable outside a class, make it class-level. You have written a method-level variable that's accessible only inside that scope (method).
To elaborate:
There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data.
So basically you know that to by extending, you should be able to access parent class data into your subclass. For that, simply make the data in your parent class as class level.
class A {
int var = 10; //class level, but non-static, so to access you need A object
void method() {
int var = 20; //this is method local and can not be accessed outside
}
}
public class B extends A {
public static void main(String[] args) {
A aObj = new A();
System.out.println(aObj.var);
}
}
Illegal start of expression (when i am delaring variable a as public)
Its illegal. Because access modifiers like public, private etc. are applicable to class-level stuff like the first var or the main method in class B you see.
Said that:
You need to immediately go here: https://docs.oracle.com/javase/tutorial/
rather than just trying to run some classes when you lack language basics.
What I really need is to be able to declare regular variables in an interface and implement that interface in two classes that I would not have to have to re-declare these in each class (ie class.data.variables instead of class.variables). Is there any way that I could achieve the same goal differently?
To give more detail. Essentially, I have created a small drawing program that drops JLabels on a JPanel that is on a JScrollPane. Because I have a specific design for these JLabels (ie they are not just for drawing they represent airline objects for this application), I have a class that extends JLabel and adds my application specific variables to it. Ultimately, I read and write an XML file with these variables so they can load and save their designs. Since I can not use this extended class for my XML definitions because it screams about the parent class even though I told it to have NONE as the accessor (I read there is a bug), I have to create an identical class and copy values back and forth for saving and loading. Not too much of a problem except when I add a variable to the JLabel extended class and forget to add it to the XML mimic class and subsequent copy routines.
So, it would be great if I could make one class (say CellDataRecord.java) that held the extra data declarations and have that class be used in both places (the JLabel extension and the XML data) without having to have something like XML.data.CellDataRecordXXX.
You can do that with inheritance or using an interface, where the variable is set as a constant in the parent class. Since you are extending a JLabel, you should implement the interface on both classes:
public interface MyInterface {
int someint = 9;
}
public class MyClass1 extends JLabel implements MyInterface {
//this class has access to `someint`
}
public class MyClass2 extends JLabel implements MyInterface {
// also has access to `someint`
}
Edit
Since you want to be able to change the same variable from different classes, you have to ensure you aren't changing copies and are changing the same variable, so you should use a volatile keyword on the variable to indicate to java that all threads should check the value before it updates it.
Now you'll need to have a separate class so that instances can be made from other classes to get the value. You have to use the static keyword to ensure that one copy is kept for all class instances.
public class MyVariableWrapper {
public static volatile int some_var = 9;
public void updateSomeVar(int newvar) {
some_var = newvar;
}
public int getSomeVar() { return some_var; }
}
Now the other two classes just do this:
public class MyClass1 extends JLabel {
MyVariableWrapper myVariableWrapper;
MyClass1() {
super();
myVariableWrapper = new MyVariableWrapper();
// now I have access to `some_var`
}
}
public class MyClass2 extends JLabel {
MyVariableWrapper myVariableWrapper;
MyClass2() {
super();
myVariableWrapper = new MyVariableWrapper();
// now I have access to the same `some_var` as MyClass1
}
// this is a wrapper method for your convenience
// since you don't like the excess code when accessing the variable
public int getSomeVar() {
return myVariableWrapper.some_var;
// or myVariableWrapper.getSomeVar();
}
public void setSomeVar(int newvar) {
myVariableWrapper.some_var = newvar;
// or myVariableWrapper.setSomeVar(newvar);
}
}
Now you can do this:
MyClass2 myClass2 = new MyClass2();
System.out.println(""+myClass2.getSomeVar());
I'm not sure I 100% grasp your problem but from the first few lines of your description, instead of implementing an interface, you could define an abstract class and have your classes extend it. That way, you'll be able to define attributes in the abstract class and these will be common to all subclasses.
Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since
we are not going to create any interface objects?
Do these inner classes help in any development process?
Yes, we can have classes inside interfaces. One example of usage could be
public interface Input
{
public static class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
public static class TouchEvent {
public static final int TOUCH_DOWN = 0;
public static final int TOUCH_UP = 1;
public static final int TOUCH_DRAGGED = 2;
public int type;
public int x, y;
public int pointer;
}
public boolean isKeyPressed(int keyCode);
public boolean isTouchDown(int pointer);
public int getTouchX(int pointer);
public int getTouchY(int pointer);
public float getAccelX();
public float getAccelY();
public float getAccelZ();
public List<KeyEvent> getKeyEvents();
public List<TouchEvent> getTouchEvents();
}
Here the code has two nested classes which are for encapsulating information about event objects which are later used in method definitions like getKeyEvents(). Having them inside the Input interface improves cohesion.
Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner").
Anyway, the following compiles fine:
public interface A {
class B {
}
}
I've seen it used to put some kind of "contract checker" directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can't). Looking like this if I recall correctly.
public interface A {
static class B {
public static boolean verifyState( A a ) {
return (true if object implementing class A looks to be in a valid state)
}
}
}
Note that I'm not commenting on the usefulness of such a thing, I'm simply answering your question: it can be done and this is one kind of use I've seen made of it.
Now I won't comment on the usefulness of such a construct and from I've seen: I've seen it, but it's not a very common construct.
200KLOC codebase here where this happens exactly zero time (but then we've got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so...).
A valid use, IMHO, is defining objects that are received or returned by the enclosing interface methods. Tipically data holding structures. In that way, if the object is only used for that interface, you have things in a more cohesive way.
By example:
interface UserChecker {
Ticket validateUser(Credentials credentials);
class Credentials {
// user and password
}
class Ticket {
// some obscure implementation
}
}
But anyway... it's only a matter of taste.
Quote from the Java 7 spec:
Interfaces may contain member type declarations (ยง8.5).
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
It is NOT possible to declare non-static classes inside a Java interface, which makes sense to me.
An interesting use case is to provide sort of a default implementation to interface methods through an inner class as described here: https://stackoverflow.com/a/3442218/454667 (to overcome the problem of single-class-inheritance).
Yes it is possible to have static class definitions inside an interface, but maybe the most useful aspect of this feature is when using enum types (which are special kind of static classes). For example you can have something like this:
public interface User {
public enum Role {
ADMIN("administrator"),
EDITOR("editor"),
VANILLA("regular user");
private String description;
private Role(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public String getName();
public void setName(String name);
public Role getRole();
public void setRole(Role role);
...
}
It certainly is possible, and one case where I've found it useful is when an interface has to throw custom exceptions. You the keep the exceptions with their associated interface, which I think is often neater than littering your source tree with heaps of trivial exception files.
interface MyInterface {
public static class MyInterfaceException extends Exception {
}
void doSomething() throws MyInterfaceException;
}
What #Bachi mentions is similar to traits in Scala and are actually implemented using a nested class inside an interface. This can be simulated in Java. See also java traits or mixins pattern?
Maybe when you want more complex constructions like some different implementation behaviours, consider:
public interface A {
public void foo();
public static class B implements A {
#Override
public void foo() {
System.out.println("B foo");
}
}
}
This is your interface and this will be the implementee:
public class C implements A {
#Override
public void foo() {
A.B b = new A.B();
b.foo();
}
public static void main(String[] strings) {
C c = new C();
c.foo();
}
}
May provide some static implementations, but won't that be confusing, I don't know.
I found a use fir this type of construct.
You can use this construct to defines and group all the static final constants.
Since, it is an interface you can implement this on an class.
You have access to all the constants grouped; name of the class acts as a namespace in this case.
You can also create "Helper" static classes for common functionality for the objects that implement this interface:
public interface A {
static class Helper {
public static void commonlyUsedMethod( A a ) {
...
}
}
}
I'm needing one right now. I have an interface where it would be convenient to return a unique class from several of it's methods. This class only makes sense
as a container for responses from methods of this interface.
Hence, it would be convenient to have a static nested class definition, which is associated only with this interface, since this interface should be the only place where this results container class is ever created.
For instance traits (smth like interface with implemented methods) in Groovy. They are compiled to an interface which contains inner class where all methods are implemented.
Is there any way other than using reflection to access the members of a anonymous inner class?
Anonymous inner classes have a type but no name.
You can access fields not defined by the named supertype. However once assigned to a named type variable, the interface is lost.
Obviously, you can access the fields from within the inner class itself. One way of adding code is through an instance initialiser:
final AtomicInteger y = new AtomicInteger();
new Runnable() {
int x;
{
x = 5;
doRun(this);
y.set(x);
}
public void run() {
... blah ...
}
};
The value returned by the anonymous inner class expression has the anonymous type, so you have one chance to use it outside of the class itself:
final int y = new Runnable() {
int x;
{
x = 5;
doRun(this);
}
public void run() {
... blah ...
}
}.x;
You can also pass it through a method declared similar to:
<T extends Runnable> T doRun(T runnable);
You can use local classes instead anonymous class. Look:
public class Test {
public static void main(String... args) {
class MyInner {
private int value = 10;
}
MyInner inner = new MyInner();
System.out.println(inner.value);
}
}
You can have reference of MyInner type only in the method body though. So outside of the method you will not be able to use its fields/methods that are not declared in its super class (java.lang.Object in this case) or interface.
public class AccessAnonymous {
private Runnable runnable; // to have instance of the class
public static void main(String[] args) throws Exception {
AccessAnonymous a = new AccessAnonymous();
a.a(); // init field
Class clazz = a.runnable.getClass();
Field field = clazz.getDeclaredField("i");
field.setAccessible(true);
int int1 = field.getInt(a.runnable);
System.out.println("int1=" + int1);
}
public void a() {
runnable = new Runnable() {
private int i = 1;
public void run() {
i = 90;
}
};
runnable.run();// change value
}
}
In the case of anonymous classes, there is also a tradeoff between the clutter caused by the class and the convenience of having it anonymous. Complicated classes rarely belong as anonymous but rather as named private inner.
In most anonymous classes, we only need to "feed" knowledge and can do it at construction.
In a few anonymous classes (e.g., return value vehicles) we also care about one return value.
As we know, data members should not directly be accessed but rather with a getter setter. This, if you find yourself in a situation that you have added lots of getters and setters, you are probably doing something wrong anyway and shouldn't be using an anonymous class.
If it implements an interface or extends an existing class, you can access the members defined in the interface or base class.
Mr Fooz is right, except that interfaces can only define constant members. the best way would be to add getter/setter methods to your interface and then use those to get your value. but then for each anonymous class you would have to define those methods (kind of a pain).
If you want readable, maintainable code, don't use anonymous classes. If you use anonymous classes and want readable, maintainable code, don't use anonymous classes when you need to access the element in that inner class. There are ways of doing so, but I beg of you to not use any of those hacks. Readability trumps all other virtues.