I have an incredibly basic question, but searching for it in the docs has done me no good, probably because I don't know what i'm searching for. I've actually completed several programs but never used this notation i'm finding in quite a few code examples I've been researching.
Up until now, when I've instantiated a class I've basically done the following:
public ClassType mclassname;
mclassname = new ClassType();
But I've seen this used:
public ClassType _mclassname;
__mclassname = new VortexView();
I can't find the documentation for the difference in the 2, but I'm thinking that it has something to do with making multiple instances of the object impossible?
If you know what I should look for to figure this out myself, that would be sufficient.
I just can't find it in the documents for instantiating classes.
Nested classes can be declared private whcih means they can only be used as a type inside the enclosing class.
Prefixing the names of class members with underscores has no syntactic meaning. It is a convention from C++ (and Python where it's specifically used to mark private members) that is not generally used in Java, but not uncommon among programmers who are more familiar with C++ or Python.
Related
Coming from a C++ environment I got used to splitting up many of the functions that I needed into an funcs.h file and then do #include "funcs.h" and then adding the functions prototypes into the main .cpp file.
Now I am starting to work with Java (mainly with Minecraft ModloeaderMp), and I already made a funcs.java file where there are some premade functions (e.g., some functions for file copying, giving stacks of items, etc.). Since I am already using the statement Public class mod_mine extends BaseModMp, is there a way I can import the functions or do I can I just do another Public class mod_mine extends funcs?
You don't #include in Java; you import package.Class. Since Java 6 (or was it 5?), you can also import static package.Class.staticMethodOfClass, which would achieve some forms of what you're trying to do.
Also, as #duffymo noted, import only saves you from systematically prefixing the imported class names with the package name, or the imported static method names with the package and class name. The actual #include semantics doesn't exist in Java - at all.
That said, having a "funcs.java" file seems to me like you are starting to dip your toes into some anti-patterns... And you should stay away from these.
There's no #include in Java.
I would not like a design that had a funcs.java that stored all the variables. Objects are state and behavior encapsulated into a single component. You aren't designing in an object-oriented way if you do that.
Good names matter. A class named Stuff that extends Stuff2 had better just be a poor example.
That's not good Java. I wouldn't consider it to be good C++, either.
It sounds like you're putting all your methods in the same class. You should separate them:
Utility classes
These should contain static methods that do things like get the contents of a file, show a dialog screen, or add two numbers together. They don't really belong in an object class, they don't require instances, and they're used widely throughout the program. See java.lang.Math for a good example of this.
Constant class or configuration files
This can be a Constants class that contains static final members, like PI = 3.1415. You can access them using Constants.PI.
Or, you can use configuration files and load them into Configuration and access the configuration variables with something like config.get("database").
Other
If your code doesn't fit into any of these, you will want to put it into some class such that your code fits object-oriented programming concepts. From your question, it sounds like you'll want to read up on this. I would first read Head First Java, then maybe some other books on object-oriented programming in Java. After that, I'd look at some design patterns.
Java is an object-oriented programming language, and there is a reason for it.
There isn't any #include in Java, although you can import classes from other packages.
Making separate class, func.java, to store variables might not be a good idea, until or unless all of them are constants.
By extending some class, you can reuse the function. But does extending class pass the is a test? If not that, this might be a bad idea.
If moving from C++, going through some good book, for example, Head First Java might help a lot.
There isn't any #include in Java. You can use the import statement to make classes and interfaces available in your file.
You can run the C preprocessor on a Java file, ensuring you use the -P flag to disable line annotations. A quick Google search confirms that this has been attempted at least twice, and is even used in the popular fastutil library:
Using C style macros in Java
https://lyubomyr-shaydariv.github.io/posts/2016-09-06-fun-with-java-and-c-preprocessor/
This works for all directives (#include, #define, #ifdef, and so forth) and is both syntactically and semantically identical to the equivalent statements in C/C++.
Actually... There is a way to have the same semantics as in C's #include (the keyword was later borrowed by C++ for the sake of looking fancy...). It's just not defined with the same words, but it does exactly what you are looking for.
First, let's see what you do with #include in C++ to understand the question:
include #defines,
"forward" function definitions (their "body" being defined elsewhere, in a class implementation, if you remember Turbo Pascal, you get my point),
define structures,
and that's pretty much it.
For the structure definitions, there isn't any point. That's old-school C: in C++ you don't define struct {} anymore for ages; you define class structures with properties and accessor methods. It's the same in Java: no typedef struct {} here either.
For this, you have the "interface" declaration (see Interfaces (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)):
It does exactly what you're looking for:
public interface MyDefines {
final CHAR_SPACE : ' '; // ugly #define
int detectSpace(FileInputStream fis); // function declaration
// and so on
}
Then, to use:
public class MyClass extends MyAncestor implements MyDefines {
...
// implementation of detectSpace()
int detectSpace(FileInputStream fis) {
int ret = 0;
char Car;
if((Car = fis.read()) != -1) && (Car == CHAR_SPACE)) ret++;
...
}
Read the link given above; it's full of useful cases.
I just came across this while reading some code and I have absolutely no idea what it means. I tried googling and whatnot but I got nothing, probably due to a lack of vocabulary. The code:
public final class GeneralPath extends Path2D.Float
{
// code and whathaveyou
}
What I know so far:
So I dont have any questions regarding the "public final class ClassName extends" portion, but I don't understand the presence of the dot/scope-resolution operator in the superclass designation. For starters, I imagine that someone is going to say something like "Java doesn't have a scope-resolution operator" to clarify some difference in nuances between Java and Cpp/other-OOP-languages, which is fine, as I appreciate knowing subtle distinctions like that. The "private" keyword killed me in a hw assignment once and I wish someone had noted the difference between "private" in Java and C then.
Im confused because clearly it is not referencing a member of the superclass, as the "member" is capitalized, and even if it were, it would seem redundant to reference a member of an object rather than just the object class itself. Furthermore, I failed to find information on the subject since most people who write java how-to's tend to start with the simpler concepts like "basic" class inheritance, and so I couldn't find anything involving the "dot" operator in relation to using the "extends" keyword.
In case I am using too many technical terms, I want to know why they used the dot operator for "Path2D.Float", or at least, what the dot operator does in this context.
Thanks a million!
The GeneralPath class is extending a class Float that is nested inside the Path2D class, which is defined something like this:
public class Path2D {
public static class Float {
// ...
}
// ...
}
I'm a beginner/intermediate programmer going from Java to C# and has been doing a little reading on functions on codeproject.com. My understanding is that namespace in C# is equivalent to packages in java. Using a namespace is the same as importing a package, though it's possible to have nested namespace. Classes exist within namespaces, and methods exist within classes. But I read somewhere that functions are class independent? Are functions not methods then? Does that mean that in C#, you can define functions outside of classes within namespaces, and can use them like methods in a class once you import a namespace? In practical usage, say if I'm trying to write a Math Library, would it be better to write functions or static methods? Are there any difference in terms of usage between the two?
As you can tell, I'm also a little mixed-up on the actual definition of a function. Is it a property (mathematical property where each input has single output) that any code can have? If yes, does that mean static methods are also functions (as long as it doesn't depend on a variable outside its scope)? Is it a special type of method/routine defined with delegate/other syntax that can be passed as parameters and assigned to variables? Responses to the question on stack overflow difference between methods and functions seems to differ quite a bit, and the accepted answer is different from the top results from googling.
I realize there are multiple questions, but they are seem interrelated (at least to me). All these definitions are bouncing around my poor head, and anything that clarifies the concept or correct my misconception would be a great help. Explanations with examples would be amazing, since I'm having trouble with the terminology. Thank you.
Let's keep it simple. No matter what the definition of functions, in C# or Java you have:
A package or a namespace which can only contain classes; not functions, nor methods.
Within a Class you have methods which would serve as functions, in the sense that they receive parameters and may output results.
You can have static methods, either in Java or C#. These methods are Class dependent, not object dependent, meaning they are called directly from a class without an object instance.
There are also entities called lambda expressions. These are objects which are defined as functions. These are used in functional programming.
And that's pretty much it. There are no functions defined directly from packages or namespaces, as there are no packages within packages nor namespaces within namespaces.
For a Math library, you may define a public Math class with all its functions, or in our case, static methods. Thus you would call: Math.sin(..), Mas.cos(...), and so on.
Note that lambda expressions serve a purpose of making some areas of programming easier, such as: SQL expressions in code, filtering collections, and so on.
Finally note that lambda expressions should not be confused with methods which belong to a class. I would suggest a nice reading from MSDN called Lambda Expressions. This reading would ease the understanding of such a nice, but dense topic.
This question already asked before but I don't find good understandable answer from there.
I would actually want to know that unlike c++ class objects can't be created statically in java why ? and what are the main disadvantages to create objects statically that java designers want to prevent to be occur ?
Thanks.
Good question. One is tempted to say that it is because the
authors of the language knew better than you what value types
you need, and provided them, and didn't want to let you define
new ones (e.g. like Complex). And there's certainly some of
that: it also explains the lack of operator overloading.
But I suspect that that wasn't the reason in the minds of the
Java authors. You need dynamic allocation and pointers (what
Java calls references) in some cases, such as when polymorphism
is involved, and the Java authors simply decided that they would
only support this idiom, rather than making the language more
complex by having it support several different idioms. It's
a pain, of course, when you actually need value semantics, but
with care, you can simulate them (java.lang.String would be
a good example) by making the class final and immutable, with
"operators" which return a new instance.
Of course, the added expressiveness of C++ does give more
possibility for errors: it's easy to take the address of a local
variable, for example, and end up with a dangling pointer. But
just because you can do something doesn't mean that you have to;
in C++, an incompetent programmer can make the program crash
immediately, where as in Java, he'll generally end up with
a wrong result (although uncaught exceptions aren't that rare
either).
Edit: It appears the poster may actually be asking why can't Objects be static in Java?, in which case, the answer is "they can" and I have added that to the answer at the bottom. If however the question is why can't Objects be allocated on the stack as they can in C++ then the first part of this answer attempts to deal with that:
I guess it boils down to the design goals of the Java language.
Because java has a garbage collector it doesn't really need to have stack allocated objects.
Trying to make things simpler, safer, familiar, while keeping them fast and consistent were design goals of the Java language designers.
Quoting from here http://www.oracle.com/technetwork/java/simple-142339.html (emphasis is mine):
Simplicity is one of Java's overriding design goals. Simplicity and
removal of many "features" of dubious worth from its C and C++
ancestors keep Java relatively small and reduce the programmer's
burden in producing reliable applications. To this end, Java design
team examined many aspects of the "modern" C and C++ languages to
determine features that could be eliminated in the context of modern
object-oriented programming.
One of those features that the designers decided was of "dubious worth" (or unnecessarily complicated the language or its Garbage Collection processes) were stack-allocated Objects.
These online chapters cover the design goals of the Java language in-depth.
Reviewing the comments I believe that I may have misinterpretted the original poster's question because the question seems to be confusing the two completely orthogonal concepts of allocating Objects on the stack with statically allocated Objects.
Stack allocation refers to value Objects that exist only within their current scope and occupy space on the stack.
Static allocation refers to instances that exist per Class - Objects that can exist for the lifetime of the application and are initialized within a static allocation block.
Java doesn't support the former concept (except with primitive data types) for the reasons explained above; but it certainly does support the latter. It is perfectly acceptable Java code to instantiate a static Object belonging to a class. A very simple example of a static Class Object would be this snippet of code:
public class Foo {
public static Integer integerValue = new Integer(32);
}
This would create a single public instance of an Integer Object that belongs to the class Foo. Because it is public in this example, one could access it and set it by calling:
Foo.integerValue = 57;
Note that only one (effectively global) copy exists of the integerValue regardless of how many Foo instances are instantiated.
A common use of statics is for class constants (declared with the the final modifier), but static variables in Java do not have to be constant: they are mutable by default if you omit the final modifier. Static variables need to be used with caution in multi-threaded applications, but that's another story.
For more information on static variables in java, you can read about them here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
and here:
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Hopefully the helps.
In a lecture on Java, a computer science professor states that Java interfaces of a class are prototypes for public methods, plus descriptions of their behaviors.
(Source https://www.youtube.com/watch?v=-c4I3gFYe3w #8:47)
And at 8:13 in the video he says go to discussion section with teaching assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?
I think the use of the word prototype in this context is unfortunate, some languages like JavaScript use something called prototypical inheritance which is totally different than what is being discussed in the lecture. I think the word 'contract' would be more appropriate. A Java interface is a language feature that allows the author of a class to declare that any concrete implementations of that class will provide implementations of all methods declared in any interfaces they implement.
It is used to allow Java classes to form several is-a relationships without resorting to multiple inheritance (not allowed in Java). You could have a Car class the inherits from a Vehicle class but implements a Product interface, therefor the Car is both a Vehicle and a Product.
What does "prototype" mean in Java in the above context?
The word "prototype" is not standard Java terminology. It is not used in the JLS, and it is not mentioned in the Java Tutorial Glossary. In short there is no Java specific meaning.
Your lecturer is using this word in a broader sense rather than a Java-specific sense. In fact, his usage matches "function prototype" as described in this Wikipedia page.
Unfortunately, the "IT English" language is full of examples where a word or phrase means different (and sometimes contradictory) things in different contexts. There are other meanings for "template" that you will come across in IT. For instance:
In C++ "template" refers to what Java calls a generic class or method.
In Javascript, an object has a "template" attribute that gives the objects methods.
More generally, template-based typing is an alternative (more dynamic) way of doing OO typing.
But the fact that these meanings exist does not mean that your lecturer was wrong to refer to interface method signatures as "templates".
"prototype" is not the the best/right terminus to be used. interfaces are more like "contracts", that implementing classes have to fulfill.
The method's heads/definitions will have to be implemented in the implementing class (using implements keyword in the class head/class definition/public class xy implements ...).
I guess this naming conventions leave much room for many ideological debates.
Or the author had some sort of a mental lapsus and mapped the construct of prototypical inheritance from javascript into java in his mind somehow.
Interfaces are not prototypes for classes in Java.
In languages like C & C++, which compiles to machine code sirectly, compiler should be aware of the nature of any identifier (variable/class/functions) before they are references anywhere in the program. That mean those languages require to know the nature of the identifier to generate a machine code output that is related to it.
In simple words, C++ compiler should be aware of methods and member of a class before that class is used anywhere in the code. To accomplish that, you should define the class before the code line where it is used, or you should at least declare its nature. Declaring only the nature of a function or a class creates a 'prototype'.
In Java, an 'interface' is something like description of a class. This defines what all methods a particular kind of class should mandatory have. You can then create classes that implements those interface. Main purpose that interfaces serve in java is the possibility that a Variable declared as of a particular interface type can hold objects of any class that implements the object.
He tells it in C/C++ way, let me explain, in C++ you can define prototypes for methods at the header files of classes so that other classes can recognize these methods, also in C where there is no class concept, you can define prototypes at the beginning of file and then at somewhere in same file you can implement these prototypes, so that methods can be used even before their implementation is provided. So in Java interfaces provide pretty much same way, you can define prototypes for methods(method headers) that will be implemented by classes that implement this interface.
In a lecture on Java, a computer science professor states that:
Java interfaces of a class are:
1. are prototypes for public methods,
2. plus descriptions of their behaviors.
For 1. Is ok: - yes, they are prototypes for implemented public methods of a class.
For 2. This part could be a little bit tricky. :)
why?
we know: interface definition (contain prototypes), but doesn't define (describe) methods behavior.
computer science professor states: "... plus descriptions of their behaviors.". This is correct only if we look inside class that implements that interface (interface implementation = prototype definitions or descriptions).
Yes, a little bit tricky to understand :)
Bibliography:
Definition vs Description
Context-dependent
Name visibility - C++ Tutorials
ExtraWork:
Note: not tested, just thinking! :)
C++:
// C++ namespace just with prototypes:
// could be used like interface similar with Java?
// hm, could we then define (describe) prototypes?
// could we then inherit namespace? :)
namespace anIntf{
void politeHello(char *msg);
void bigThankYou();
}
Prototypes provide the signatures of the functions you will use
within your code. They are somewhat optional, if you can order
your code such that you only use functions that are previously
defined then you can get away without defining them
Below a prototype for a function that sums two integers is given.
int add(int a, int b);
I found this question because i have the same impression as that teacher.
In early C (and C++ i think) a function, for example "a" (something around lexic analysis or syntactic, whatever) can not be called, for example inside main, before it's declaration, because the compiler doesn't know it (yet).
The way to solve it was, either to declare it before it's usage (before main in the example), or to create a prototype of it (before main in the example) which just specifies the name, return values and parameters; but not the code of the function itself, leaving this last one for wherever now is placed even after it's called.
These prototypes are basically the contents of the include (.h) files
So I think is a way to understand interfaces or the way they say in java "a contract" which states the "header" but not the real body, in this case of a class or methods