How can the method getSequencer in JavaSound API return an instance of the interface Sequencer?
Sequencer sequencer=MidiSystem.getSequencer();
I have read that we cant create an instance of an interface.
static is a very troublesome concept at best, its greatest akin for trouble at explaining is "volatile" keyword declaration.
You would have less trouble with "synchronized" keyword on a code block than the previous two for explaining their usage parameters and concept!
"static" is not constructed as "new" because it is not a "separate instance" it is already available when compiled in as a static object.
All interfaces in Java are abstract but have "static" fields(variables) only,
ONLY ONE of those loaded static class instruction version of AKA(A Kind of Alias) "instance" of a class(or alternately interface) will be present at that class hierarchy level on the process in the JVM runtime in that particular "user classes" hierarchy structure of call for any number of classes created that commit call of a static object or a static method (static code DOES NOT MAKE A NEW SEPARATE SET OF INSTRUCTION IF CALLED CONCURRENTLY FROM VARIOUS CLASS COPIES).
With anything "static" there is only one copy in use for all of the program at that calling class on the PID process level in the JVM during runtime.
You cannot instantiate MidiSystem because all its methods are "static"
So to use ANY static class to call one of its static methods from it (or the same on an interface)
you only use its class name followed by the dot operator on its method you wish to call.
Exactly as you have it in the code and syntax you posted. (NOTE "Sequencer" is actually static )
But if you need your variable non static to remove static you cast it if the class type to cast to is non static, only if the class you are casting is not itself an actual "static" compiled class !
e.g. DriverManager.getDriver() for JDBC database running more than one connection concurrently cannot use static driver copies or there would only be one copy available in use of during runtime with the instructions template (the class byte code for the static class) !
To remove "static" from an object, the object must be cast to non static into a variable of same object type that is not of static notation(declared).
// the getDriver() method is static inside class DriverManager ,
// Driver is an Interface not a class
Driver driver = (Driver) DriverManager.getDriver( configuration.jdbcUrl() );
// After casting, there is now a separate non static reference of Driver
// interface , so **note that neither MidiSystem or DriverManager class are**
// actually declared static and both have no constructor and not declared
// abstract but contain only static methods !
an "INSTANCE" is something you construct , so another one is a new instance !
Interfaces are not constructed, they operate much more alike "abstract" and "static" declarations.
Using the class name only is the syntax of calling EITHER abstract or static classes to obtain their methods.
A final point , to refer to an interface as a "data type" is to make a reference variable to represent it because an interface IS a data type (known as an object) the same as a class or abstract class.
So your above code has "Sequencer" interface as a data type.
When a class "implements" an interface the class itself can be cast to that interface because it is ALSO that object type.
e.g.
public class Example implements Extra{.....}
Extra example = (Extra)new Example();
// next below shorthand implicit cast is compiler dependent
public class Example implements Extra{.....}
Extra example = new Example();
If you do not implement an interface in a class the interface can be called into the code with assignment of a reference variable by using a class that has a method that obtains that interface data type.
There is a huge relationship between abstract classes and interfaces but they are not the same.
Abstract classes do not have global variables.
Interfaces do have global variables but all of them must be static and final. Abstract classes cannot have any global variables or it would be an "instance of a class" and would then require to be constructed as "new".
Abstract classes have less strict rules on method declaration than interfaces.
Abstract classes can have most class modifiers interfaces are all public
Interfaces have "default" modifier for methods that contain an implementation body of code or must be static method.
In short the variable for Sequencer interface is not an instance variable, it is a reference and (clause for static) you are referring to something defined as "static" so IT MUST be there when the class that calls it starts !
Related
On the subject of Anonymous classes, the Oracle documentation states that...
They are like local classes except that they do not have a name. Use them if you need to use a local class only once
Now, given that local classes are (to my knowledge) classes defined within a method (or some other local construct) like the following...(where 'MyInterface' is an interface with an abstract 'test' method)
public void localTest(){
MyInterface mi = new MyInterface(){
#Override
public void test(){System.out.println("test");};
};
}
The above is OK and falls within the definition above, however, I can also define the following...
class MyClass{
MyInterface mi = new MyInterface(){
#Override
public void test(){System.out.println("test");};
};
}
This isn't within a method so isn't a 'Local' class and therefore doesn't fall within the above definition. Is there anywhere I can read about these types of anonymous classes (anonymous member classes if you will). What exactly are they if not anonymous classes as defined?
Both examples you show are anonymous classes. A true local class is a class definition in a method (or other code block), with an actual name (so, not anonymous). Given your example, an equivalent local class would be:
public void localTest(){
class LocalClass implements MyInterface {
#Override
public void test(){
System.out.println("test");
}
}
MyInterface mi = new LocalClass();
}
In my opinion you should hardly ever need a local class. I think I have only tried to use it once, to only quickly refactor it when I got a grip on what I actually needed.
The most important difference between local classes and anonymous classes is that you can reuse a local class within the same method (that is create multiple instances in the same method; without resorting to loops or lambdas).
Furthermore, as you actually have class definition, you can also define and call methods that aren't defined in the interface or super-class. Prior to Java 10 and the introduction of var, this was not possible with anonymous classes.
Other minor differences are that local classes can be abstract or final, and local classes can extend (and be extended by) other local classes, while an anonymous class is not final and cannot be abstract, but anonymous classes cannot be extended by other classes.
For more information regarding the difference between local classes and anonymous classes, see the Java Language Specification, specifically 14.3. Local Class Declarations and 15.9.5. Anonymous Class Declarations and related sections.
Local classes are defined here as being defined in a block, rather than in a method. Your example is still an anonymous class. If you're in the process of learning, a note here is that you can actually replace the declaration with a lambda expression like so:
MyInterface mi = () -> System.out.println("test");
Also, anonymous classes are only described as being like local classes, meaning that the former is not necessarily a subset of the latter.
Why can't constructors be final, static, or abstract in Java?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
The question really is why you want constructor to be static or abstract or final.
Constructors aren't inherited so can't be overridden so whats the use
to have final constructor
Constructor is called automatically when an instance of the class is
created, it has access to instance fields of the class. What will be
the use of a static constructor.
Constructor can't be overridden so what will you do with an abstract
constructor.
A Java constructor is implicitly final, the static / non-static aspects of its semantics are implicit1, and it is meaningless for a Java constructor to be abstract.
This means that the final and static modifiers would be redundant, and the abstract keyword would have no meaning at all.
Naturally, the Java designers didn't see in any point in allowing redundant and/or meaningless access modifiers on constructors ... so these are not allowed by the Java grammar.
Aside: It is a shame that they didn't make the same design call for interface methods where the public and abstract modifiers are also redundant, but allowed anyway. Perhaps there is some (ancient) historical reason for this. But either way, it cannot be fixed without rendering (probably) millions of existing Java programs uncompilable.
1 - Actually, constructors have a mixture of static and non-static semantics. You can't "call" a constructor on an instance, and it they are not inherited, or overridable. This is similar to the way static methods work. On the other hand, the body of a constructor can refer to this, and call instance methods ... like an instance method. And then there is constructor chaining, which is unique to constructors. But the real point is that these semantics are fixed, and there is no point allowing a redundant and probably confusing static modifier.
public constructor: Objects can be created anywhere.
default constructor: Objects can be created only in the same package.
protected constructor: Objects can be created by classes outside the package only if it's a subclass.
private constructor: Object can only be created inside the class (e.g., when implementing a singleton).
The static, final and abstract keywords are not meaningful for a constructor because:
static members belong to a class, but the constructor is needed to create an object.
An abstract class is a partially implemented class, which contains abstract methods to be implemented in child class.
final restricts modification: variables become constant, methods can't be overridden, and classes can't be inherited.
Final: Because you can't overwrite/extend a constructor anyway. You can extend a class (to prevent that you make it final) or overwrite a method (to prevent that you make it final), but there is nothing like this for constructors.
Static: If you look at the execution a constructor is not static (it can access instance fields), if you look at the caller side it is (kind of) static (you call it without having an instance. Its hard to imagine a constructor being completely static or not static and without having a semantic separation between those two things it doesn't make sense to distinguish them with a modifier.
Abstract: Abstract makes only sense in the presence of overwriting/extension, so the same argument as for 'final' applies
No Constructors can NEVER be declared as final. Your compiler will always give an error of the type "modifier final not allowed"
Final, when applied to methods, means that the method cannot be overridden in a subclass.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
No Constructors can NEVER be declared final. YOur compiler will always give an error of the type "modifer final not allowed"
Check the JLS Section 8.8.3 (The JLS & API docs should be some of your primary sources of information).
JLS section 8 mentions this.
Constructors (§8.8) are similar to methods, but cannot be invoked
directly by a method call; they are used to initialize new class
instances. Like methods, they may be overloaded (§8.8.8).
But constructors per say are not regular methods. They can't be compared as such.
why constructor can not be static and final are well defined in above answers.
Abstract: "Abstract" means no implementation . and it can only be implemented via inheritance. So when we extends some class, all of parent class members are inherited in sub-class(child class) except "Constructor". So, lets suppose, you some how manage to declare constructor "Abstract", than how can you give its implementation in sub class, when constructor does not get inherit in child-class?
that's why constructor can't be
abstract .
lets see first
final public K(){
*above the modifier final is restrict 'cause if it final then some situation where in some other class or same class only we will override it so thats not gonna happen here proximately not final
eg:
we want public void(int i,String name){
//this code not allowed
let static,, static itz all about class level but we create the object based constructor by using 'new' keyword so,,,,,, thatsall
abstract itz worst about here not at 'cause not have any abstract method or any declared method
Unfortunately in PHP the compiler does not raise any issue for both abstract and final constructor.
<?php
abstract class AbstractClass
{
public abstract function __construct();
}
class NormalClass
{
public final function __construct() {
echo "Final constructor in a normal class!";
}
}
In PHP static constructor is not allowed and will raise fatal exception.
Here in AbstractClass obviously a constructor either can be declared as abstract plus not implemented or it can be declared as something among (final, public, private, protected) plus a function body.
Some other related facts on PHP:
In PHP having multiple constructor __construct() is not possible.
In PHP a constructor __construct() can be declared as abstract, final, public, private and protected!
This code was tested and stood true for in PHP versions from 5.6 up to 7.4!
The "abstract" keyword means you cannot create an instance of the class (an object).
Java.Lang.Math is preceded with the following keywords
public final class Math {
...
}
But no "abstract" keyword. The class simply provides a collection of related static variables and methods, like PI and sin().
Static means that those variables/methods can't be unique between different instances of the object (there is only one copy of those variables/methods associated with the class itself). So why even allow the programmer to create an instance of the class? Why not precede with "abstract"?
final and abstract keywords can't be applied together because final class can't be overridden and abstract classes are meant for override.
A class that is declared final cannot be subclassed that is used for creating an immutable class such as String
It's better explained under JSL section - 8.1.1. Class Modifiers
An abstract class is a class that is incomplete, or to be considered incomplete.
A class can be declared final if its definition is complete and no subclasses are desired or required.
both above statements are contradicting each-other.
If you want to read more about then have a look at Java Tutroial on A Strategy for Defining Immutable Objects
Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
Make all fields final and private.
Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects.
java.lang.Math is a Utility class (contains only static utility methods).
Correct way to define utility class is to make it final so that no other class can extend it and to have private no-args constructor so that no one can create an instance of the class.
So you won't be able to create instance of class any how. However if you go by abstract approach, you cannot use final and there is no way you can prevent it from being extended. Hence former approach is better.
If it were abstract, someone could do
public class NewMath extends Math {
which frankly speaking makes no sense.
However, you cannot create a new Math instance anyway because its only constructor is private:
private Math() {}
final means you cannot extend it, the reason you cannot create an instance is because the constructor is private. This is how (in java) you define static classes or factory classes.
The Abstract keyword means the class can't be Instantiable but it can be Extended.
And in case of Utility Classes such Math Class,Extending it has no sense. Declaring the no-args Constructor makes it Non-Instantiable and final makes it non-Extendable...So its the Perfect Match .... And If you use Abstract then you can't use Final...
In an Interface by default the data member are static and final.
Static it is because it can not be instantiated,but why it is final?
and the other question is even the abstract classes can not be instantiated,then why it can have a non static data member??
and the other question is even the abstract classes can not be instantiated,
then why it can have a non static data member??
Because in abstract classes, you can define as much functionality you want, which can be then used by its childs.
Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
I wouldn't advise on putting variables in an interface since the interface mainly serves as a blueprint for it's classes.
Why can an abstract class have a non-static data member?
A static variable is one that’s associated with a class, not objects of that class. Generally speaking, the purpose of an abstract class is to provide a skeleton with some non-abstract behavior, but other bits still to be filled in by subclasses which can also define functionality and use the abstract class' variables.
I've been wondering why it's allowed to do a code implementation in an interface, when interfaces are suppossed to contain no code implementation:
public interface someInterface{
String someString = "example";
}
I can make a class implement this interface, without getting an error:
public class someClass implements someInterface
How come?
You are allowed to declare constants in interfaces, which is what you have done. You have not implemented code.
Variables declared in interfaces are implicitly declared public static final.
The JLS, Section 9.3, covers this:
Every field declaration in the body of an interface is implicitly
public, static, and final. It is permitted to redundantly specify any
or all of these modifiers for such fields.
According to java docs
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
Here you are not defined any methods to implement.So you didn't get any error here.
There is no strict condition that an interface must have signatured methods.Remember there are Marker Interfaces too in java.
And secondly , You can declare variables inside interface.
And that variable someString assigned in a static context and shared across all the implemntations by that interface
Point is that the variables inside declared interface are implicitly static and final.You can use them.