Different ways to create classes? - java

I've been practicing making GUI in netbeans and came across this auto generated code
saveButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
saveButtonMousePressed(evt);
}
I'm just confused in the argument "new java.awt.event.MouseAdapter()". I know that when we use the "new" keyword we make an object of that class. But after that "new" statement it declared a method so my perception was that "an object with a method? I know we create object so that we can use methods not create a method within them".
After researching and reading about Inner Classes, I now have a different perspective.
Would that be possible to create a class in a argument with the "new" statement? if true then that code didn't created a object, but instead created a class.
If my conclusion would be right there are 2 ways (I know so far) to create classes in java.
by using,
public clas Sample() {
//insert methods here
}
and by using,
public void getSomething(new Sample() { //insert method here })
Did I get this one right? I'm just a beginner in java(Self Study).

It's not a different way to create a class, actually you define it in the same way you would with any other class but you don't name it, it is just a specialized MouseAdapter.
What actually happens is that you define a specialized version of mousePressed without the need to associate it to a named subclass of MouseAdapter. It's like defining and using the class in the same point. You define a specific class with specific behavior and instantiate it.
Indeed that's called an anonymous class. This has nothing in common with an inner class, which is a class that is defined inside another class (so they are nested).

Related

In what situations can methods of one class be invoked on objects of another?

I'm new to Java so I'm still learning the rules of working in a strictly object-oriented language. Today I was wondering about using a method to work with objects outside of that method's class. Is it possible under any circumstance to successfully perform operations on an object with a method from another class?
Say I have an anchorPane object (javafx). It would not be sensible to try to invoke the setText() method of the Text class on it, because anchorPanes do not display text directly.
But, are there situations in which such a thing is possible? Is it always a rule that methods can only affect objects of their class?
Is it always a rule that methods can only affect objects of their class?
not directly, but if you mark a method as protected, the method can be invoked only from objects of same class and objects from derived classes (even on other instances). See also https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
In addition, you can make it final, so that it is not possible to overrule the method (and if you make your class final, nobody can derive from your class). in this case, you get exactly what you described:
//final here disallows to subclass "Sample". This assures that there exists NO subclass that invokes bar().
public final class Sample {
public void foo() {
//on same instance
this.bar();
//on another instance, but just same class (or subclass of Sample, but not possible because class is final)
Sample b = new Sample();
b.bar();
}
/*final here prevents that METHOD is overwritten. But class can be overwritten.
* subclasses are also allowed to invoke bar().
*/
protected final void bar() {
//do something here
}
}
In what situations can methods of one class be invoked on objects of another?
Every class (and interface) defines methods that can be invoked on it.
Java being a typesafe language, it does not allow you to invoke a method written for a specific class on something that is not an instance of that class (something you could do in Javascript for example, by using bind(iWantThisThis)).
It is not possible to invoke these methods on instances of completely unrelated classes. They would need to be of that class or of a subclass.
So, no, you cannot invoke Text::getText on an instance of the unrelated AnchorPane.
You can invoke common methods from a shared parent interface or superclass. For example both anchorPane.toString() and text.toString() will work (because every Object in Java has these methods). If AnchorPane and Text both happen to be implementing a hypothetical UIComponent interface, there might be a getSize() method on both of them.
What I think you are looking for is called delegation or object composition. If you have an AnchorPane that displays a Text, you can give it a method that is also called setText that delegates the method call to a Text instance contained in the AnchorPane.
class AnchorPane {
private final Text myText;
void setText(String newText){
myText.setText(myText);
}
}
So now you also have a setText method on AnchorPane (but you had to add it manually to specify what exactly it does, and it does not give you any of the other methods).

visual example of passing object into another objects constructer? [duplicate]

I was reading a textbook and I was wondering how come the argument we pass to the function is neither a primitive or an user-defined instance of a class.
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new ButtonDemo();
}
});
I have learned that it was either one of those two. But it seems here that it passes an user-defined constructor method, e.g. Runnable(). It seems they want to run the thread at a later time, but when? And is this even legal, I assume it is, but I never heard of such a thing in my Java class.
This is actually passing an instance of an anonymous inner class implementing the Runnable interface. Read about them in the Java tutorial.
I was wondering how come the argument we pass to the function is neither a primitive or an user-defined instance of a class.
It is an instance of a user-defined class. The only difference is that this class does not have a name *.
It is a real instance of a class, though - it can do most of the things a named class can do. Among other things, it can provide implementations of methods of its base class or an interface, which is what is used to pass "a piece of executable code" to a method.
* At least, not a user-visible one: Java compiler does assign each anonymous class an internal name, which usually contains a dollar sign.
The code inside SwingUtilities is something like this
private Runnable runnable;
private void invoke(){//called at some point from inside the runnable
runable.run();
}
public void invokeLater(Runnable runnable){
this.runnable=runnable;
}
These are called callbacks.
This called anonymous class, where you define a class for a single use and do not provide it a name.
To understand them better, refer to this tutorial: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Read about Anonymous Classes. This are treated as separate classes. If you compile your code and say the file name is Test.java. By compiling there will two class file Test.class and Test$1.class and if you have more inner classes you will have Test$2.class, Test$3.class and so on.
Passing code as function arguments
Java will have lambda expressions in release 8. It will worth checking out this as well: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

How do I change part of a parent class's constructor when inheriting from it?

I've got some class and I want to make an object out of it. However, this class has a property set in its constructor that makes it unusable for me. I cannot edit this class's code as it exists in a very tight codebase. This property cannot be changed after the object is constructed, so even if there WERE a setter method, it wouldn't work (it's part of the SWT gui framework, and can't be changed dynamically).
My instinct tells me to subclass it and change what I need to change. Should only take a few lines because every other aspect of this class will stay the same. However, since the first line you need to call in a child class's constructor is the super method, that means the parent class's constructor is called before I can even do anything.
Is there ANY way I can make an object out of this class with just ONE small property changed, without having to create an entire new class that's a copy/paste of all its code, except for one small change in like 8?
Thanks!
EDIT: since someone requested code:
public class Parent {
private Object important_object = null;
public Parent() {
important_object = new Object();
important_object.important_property = BAD;
}
}
public class Child extends Parent {
public Child() {
// how the heck do I make an instance of this
// class that has important_property set to GOOD
// instead of BAD?
}
}
If the attribute is private, no setter to either important_object or important_property is provided and you cannot use Reflection then there is no way to change the attribute.
There is something called classworking, that allows you to modify the Java bytecode in runtime, but it's definitely non-trivial and it probably is way too much for this. Although it's a very interesting read.
http://www.ibm.com/developerworks/library/j-cwt02076/
https://commons.apache.org/proper/commons-bcel/

Understanding the difference between extending a class and importing a class [duplicate]

This question already has answers here:
What's the difference between importing and extending a class?
(10 answers)
Closed 7 years ago.
I have seen several threads that define extending a class as a way for a personalized class to inherit the methods of the class that it is extended to. When you import a class and create an instance of that class you have access to its methods, can someone please explain to me how extending a class to provide those methods to your own class is effectively different, in other words, the only difference I see is that when you import you create an instance of a standardized class, and when you extend you effectively turn your personalized class into the standardized class only with a different name. I am aware I am wrong, but the answers I have read have failed to help me fundamentally understand the difference.
Importing and extending are two very different things.
Importing
Classes are organized in packages, which provide a namespace facility that avoids name conflicts. Importing allows you to use the class in your code without the namespace information.
Importing is optional. You never have to import anything if you always use the fully qualified name of the class, but that makes your code hard to read.
If you want to make a list of Calendar objects, for example, you either import java.util.List, java.util.ArrayList and java.util.Calendar and use:
List<Calendar> array = new ArrayList<>();
Or import nothing and use:
java.util.List<java.util.Calendar> array = new java.util.ArrayList<>();
Sometimes you have two classes with the same name in different packages. In that case, if you use both of them in your code you can't import both. You will have to refer to one of them by their fully qualified name. For example:
List<java.awt.List> array; // you have to import java.util.List, but can't also import java.awt.List
Extending
When you extend in Java you are saying that the subclass is a type of the original class. That's the most important aspect you have to be aware of when using extends. Is you say Bus extends Vehicle you are saying that Bus is a Vehicle. You not only inherit all the non-private methods and fields of the superclass, but also can use the subclass anywhere you could legally use the superclass. For example, if you have this method:
public park(Vehicle v) {
v.drive();
v.turn(Direction.LEFT);
v.stop();
}
you could pass a Bus as an argument, because Bus is a Vehicle.
parkingLot.park(new Bus());
and the drive(), turn() and stop() methods will be called in the Bus. That is polymorphism.
Although you inherit methods, inheritance is not the best way to reuse code. Most of the time when you need to reuse code you can do it by using composition (making your class have a reference to another class, instead of being one). A Car shouldn't extend Motor because a car is not a motor, but it could have a motor and delegate a call to the motor's turnOn() method when the car's drive() method is called.
You can also have polymorphism without inheritance in Java using interfaces.
To make a simple example (but bad :/ ). Lets say you have a Person class.
public Person
{
int age;
string name;
}
Then you have different type of persons that inherit the Person class, eg.
public SoftwareDeveloper extends Person
{
string codingLanguage;
}
Now you can easily create a SoftwareDeveloper and use its attributes like this:
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.name);
}
If you would "import" instead, you would have to create an instance of Person in SoftwareDevelopers constructor and make it public. So your code would be to access the attribute:
public SoftwareDeveloper
{
public Person person;
string codingLanguage;
public SoftwareDeveloper(){
person = new Person();
}
}
public static void main ()
{
SoftwareDeveloper developer = new SoftwareDeveloper();
System.print.out(developer.person.name);
}
I think in small scale your reasoning works fine but the idea of extending is that your class inherits all the methods of the extended class.
But if you start with a simple idea or program and want to expand it massively the use of instantiating all the classes you need becomes much more consuming. On even a simple idea the increase in imports can explode.
Example:
Animal - warm blooded - biped - human
Animal - warm blooded - quadruped - feline - cougar - panther
Now you want to have your panther have all the methods of the 5 classes its built apoun.
So that 5 imports and objects you have to manipulate to get to all the methods you want to access. But if all these are extending each other you just have direct access to the methods. And this is a simple example now imagine a huge accounting program.
So point I trying to make....I think...Is that its much more prevalent and easier to understand the usefulness in extending classes when you look at it in the large scale.
Hope this helps or makes as much sense as it does to me.
Extending a class means that your class is "inheriting" the methods of the standard class; in other words, you are taking an existing class and building your class on top of it. That is how Java manages all objects (i.e. every class that you create actually extends the default Object class). When you import a class, on the other hand, you have access to all its functionality, but you cannot build on top of it as you could with inheritance.
Let's start with importing a class. You import a class in order to use it in another class, if that class is in another package. It's really just a shortcut that's saying when you see a class called X used, what I really mean if com.somepackage.X.
Extending is taking a class and using it as a base for a new class. There's alsorts of reasons to do this (well beyond the scope of an answer here) but the important thing is that you inherit the behaviour of the class you are extending and have the choice of whether or not to override that behaviour or add additional behaviour.
For good example of classes being extended, look at the Collection API in java.util where you can see java.util.AbstractList is extended to ultimately create two different types of list, each with different characteristics - java.util.ArrayList and java.util.LinkedList.
Lets look on an example.
We have class which provide an update function to database and containing a String variable.
public class DBupdate {
public String StrVar = "Hello";
...
public void doUpdate(String expression) {
try {
connect();
runExp(expression);
disconnect();
} catch ...
}
}
If you import it. You will do something like
log(new DBupdate.StrVar);
String myExp = "UPDATE ..."; // SQL
new DBupdate.doUpdate(myExp);
If you extend.
log(StrVar);
String myExp = "UPDATE ..."; // SQL
doUpdate(myExp);
doUpdate() function and StrVar became part of your new class. So all functions and variables (which are public or protected) are part of your new class (inherited).
Example for usefull import (and not extend/inherit) is log4j. It is doing work like writing to console and into a file. But you want just to use it "log" function and no speacial functions it is using for its work.
Example for usefull inherit is java.lang.Thread. If you class became a thread it can be treated as a Thread and will be splitted to run parallel, if you use java.lang.Thread function "start()". (Override run() method to do so some stuff...)
At the very simplest case it can be said that, Import Statement improves readability and reduces the length of the code.
In java we implement dynamic loading, language import statement no class file is loaded at the time of import statement, when ever we are suing a class, at the time of only the corresponding .calss file will be loaded.
Extends-
In Java, when we wish to extend the usefulness of a class, we can create a new class that inherits the attributes and methods of another. We don't need a copy of the original source code (as is the case with many other languages) to extend the usefulness of a library. We simply need a compiled '.class' file, from which we can create a new enhancement. I could not find a better way to explain so just refer this link..(source -http://www.javacoffeebreak.com/java104/java104.html)

Can I create static methods on #MappedSuperclasses?

I have an abstract TemporalModel class (annotated with #MappedSuperclass) that adds created and updated fields to all extending models. I want to add a getLatest() static method to it:
public static TemporalModel getLatest() {
return find("order by created").first();
}
When I put this method on the base class, and call it through a concrete class (Transaction.getLatest()), I get an error:
UnsupportedOperationException occured : Please annotate your JPA model
with #javax.persistence.Entity annotation.
I suspect this is because JPA doesn't in fact know I'm calling this method "through" the base class (there is no real static method inheritance in Java).
Is there another way to implement this method once, instead of repeating it on all entity classes?
Update - one way to achieve this (which I'm using in another heavier app) is described here (gist). In my current app, however, I wouldn't like to use repositories, and I wondered if there's another, lighter solution.
Constructors and static methods can never be abstract. The idea behind an abstract class
is to create blueprints of methods, that have to get worked out in the subclass(es). I suggest trying an interface TemporalModel instead of an abstract class, in which you create the method public static TemporalModel getLatest();
I haven't used this Play framework, so I'm not sure about the details here, but usually, when one does the stuff you want to do, in Java, one simply specifies the concrete class as a parameter to the static method in question. It's kind of ugly, of course, but it is Java.
I assume that this find method is a static method that is added somehow (by annotation processing?) by this framework on every extending class, right? In that case, I think your only recourse is to do something like this:
public static <T extends TemporalModel> T getLatest(Class<T> cl) {
try {
/* I don't know what type the find() method returns, so you'll have to fix the casting */
return(cl.cast(cl.getMethod("find", String.class).invoke("order by created").first()));
} catch(AllThosePeskyReflectionExceptions e) {
throw(new Error(e));
}
}
I think that's the best way available given the premises. I know it's ugly, so I'd be happy to be wrong. :)

Categories