Just had this in a unit test. So:
abstract class A {...}
class B extends A {...}
A a = new B();
Pretty much doubt it's viable, but I'm totally confused at the moment. The content of the classes is irrelevant.
yes this concept is known as polymorphism in java . a parent can contains reference of child class. and parent can be either interface or abstruct class. even you need not to cast . for example .
a animal can be horse or cat , here animal is an interface or abstract class.
i recommend (SCJP Sun Certified Programmer -kathy sierra)book has lot of concepts related to java language.
Its valid in java. this is called implicit up casting (JVM casts sub type to super type object) where reference of super type can refer to sub type but with super type reference you can only get access to only those variables and methods which are declared/defined in super type.
Yes this is valid in java
abstract class A {...}
class B extends A {...}
A a = new B();
Yes this is a valid java assignment statement.
A a = (A) new B();
In java a child object can be referenced from the parent class.
It's valid.
As per Java's fundamental rule "Super class reference (A a) can refer sub class object (b= new B())".
Interface - every method is always public and abstract whether you are declaring it or not. You can’t declare an interface method with the following modifiers. Every variable present inside interface is always public static and final whether we are declaring or not. You can’t declare an interface variable with the following modifiers, private, protected, transient and volatile. The variables present within abstract class don’t have to be public, static and final. There are no restrictions on abstract class variable modifiers. For abstract class variable are not required to perform initialization at the time of declaration. An abstract class can declare instance and static blocks. Inside interface we can’t declare instance and static blocks otherwise we will get compile time error. Interface can’t declare constructors. Just keep these fun facts in mind.
Related
Why does class ref type and interface ref type have a different access scope of their methods.
In the following example
interface ImInterface{
void do1();
void do2();
}
class MyClass implements ImInterface {
void do1(){
System.out.println("do1");
}
void do2(){
System.out.println("do2");
}
void do3(){
System.out.println("do3");
}
}
Could you help me understand why mc variable defined like
MyClass mc = new MyClass();
cannot access do1 and d2 without any cast? It implements all functionality from contract (ImInterface). Why is it like this in Java?
Also, why mi defined like
MyInterface mi = new MyClass();
cannot access do3 without any cast?
I know both mi and mc have different types, but after implementations both become one now, then why it's a difference to access without cast? mc and mi both point to same type of instance.
Since you are declaring the object mi as of type MyInterface, you will only have access to the methods that are declared on MyInterface.
When you declare the object mc as of type MyClass, you will have access to all the methods declared in MyClass and its superclass.
When Java looks at the reference mi, it will just know that it is of type MyInterface.
Now if you declared mc outside of the package then you won't be able to access any of their methods because they have package visibility.
Why mc cannot access do1 and d2 without any cast ?
It can, provided you call mc.do1() or mc.do2() from a class within the same package where MyClass is declared. In Java, when you don't declare an access modifier for a method or a field, Java allows it to be accessible only within the same 'package' where the class is declared. For do1() and do2() to be accessible anywhere, declare them with a public 'modifier':
public void do1() {
...
}
Note: This is not applicable for interfaces as all methods in interfaces are by default 'public', even when the keyword is not specified.
Why mi cannot access do3 without any cast ?
That's how Java is designed. An interface specifies a contract (what, and not, how). So when a class implements an interface, it has to adhere to that contract, plus it can declare it's own functionalities. But as long as you refer to the object of the implementation class with the reference of the interface:
MyInterface mi = new MyClass();
the interface reference will be able to access only the method it has declared. In other words, the interface reference can only tell what it 'knows for sure' to be present in the implementation (as the implementation class has implemented the interface) and not the other functionalities (methods) of the implementation class.
Methods of an interface are implicitly public and methods of a class with no specified access modifier have weaker access privileges than public.
When you implement an interface's method, the implementing class cannot have weaker access modifier for it than specified in the interface.
In your example you are trying to implement an interface with implicitly public methods through methods that have no modifier, violating the rule above. If you want to make this code work, you should make these methods explicitly public.
mi cannot access do3() because it has no information about this method in ImInterface declaration (and mis type is ImInterface). This is the reason you have to explicitly cast mi to MyClass, telling Java that it can treat this object in by more "narrow" means.
You can find more information about interfaces here.
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 !
I'm reading Java Inheritance Docs and got this paragraph, but I don't what is mean of this. Can any body explain?
Excepting Object, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of
Object.
Edited
Another point related to this question:
And due to Object is superclass, NetBeans show me extra method list when I try to call any Member of class with object reference? All those methods are declared in Object class?
It means that,in java the Object class is the parent class of all the classes by default. In other words, it is the topmost class or the base class of java. All other classes inherit the properties of Object class.
Meaning of implicitly - suggested though not directly expressed.
If samething applied in Java classes. Consider there is a class called Test.
If you write
public class Test {....}
That is equivalent to
public class Test extends Object {....}
Though you didn't write it, it's equivalent to it. You need not to write extends Object manually. Internally JVM treats that your class is extends Object. Since the part after extends is your class, here Object is your super class.
But,
When you write
public class Test extends BigTest{....}
Things changed now. You are telling BigTest is my parent class. That means you are implicitly writing yourself that BigTest is my parent. Interesting part here is though BigTest is your direct Parent class, internally Object also your Parent.
So now you have 2 parent classes. One is BigTest which you mentioned and other is Object. If you didn't mention anything, only Object is your Parent.
Edit :
This is the reason that you will see extra list of method when you will try to call any member of class with object-reference. Those methods are declared in Object class.
why java do this? any feature of this?
Yes. There are benefits of it. Main reason is to reduce the code duplication.
Continue reading here .... Why Object as super class in Java ?
It means that the following two classes are the same:
class MyClass {
}
class MyClass extends Object {
}
If a class definition doesn't specify extends, the class implicitly extends Object.
The Object class comes with the JRE, you use any class without it. Java does this so you can have a reference to any object e.g.
Object o = x;
This works because no matter what x is, it is also an Object.
Note: even int[] class is a sub-class of Object.
I'm new on Java, reading the Sun basic tutorial and see "The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. " I wonder how can Object be the root parent of the class I defined if my class did not inherit from other classes.
If you continued reading on the same page
(emphasis mine):
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
This is an implicit behavior. All of your classes extend Object (directly or not).
public class MyClass is equivalent to public class Myclass extends Object
That's the "magic" done by the Java compiler: when you write
public class MyClass {
...
}
Java compiler sees it as
public class MyClass extends java.lang.Object {
...
}
It works that way because the Java Language Specification (specifically section 8.1.4) says so:
Given a (possibly generic) class declaration for C<F1,...,Fn> (n ≥ 0, C ≠ Object), the direct superclass of the class type C<F1,...,Fn> is the type given in the extends clause of the declaration of C if an extends clause is present, or Object otherwise.
If I have a class C which inherits class B and class B inherits class A, then
If I create an object of Class C, is the object of superclasses created?? If yes, how??
How to access the private members of class A??
Does the object of superclass created when object of derived class is created?
No.
The superclass constructor is used to initialize the superclass-defined state of the currebt object, but this does NOT amount to creating an instance of the superclass.
If I have a class C which inherits class B and class B inherits class A, then If I create an object of Class C, is the object of superclass created??
No. See above.
If you create an instance of C, you will have one object whose most-derived type is C. This object will also be an instanceof B, but it may not behave exactly like a regular B due to method overriding in C and other things.
If yes, how??
Moot.
How to access the private members of class A??
You cannot directly access the private members of a superclass from a subclass. That is what the private access modifier means. If you need to access them you need to use them, you either need to create non-private methods in the superclass to do this (e.g. getters and/or setters), or change the members' access.
(An alternative is to use reflection to override the private access modifiers, but you should only use that as a last resort. It is better to fix the superclass code to provide the required access ... or figure out away that the subclass doesn't need access at all.)
yes, the object of super class is created.
You cannot access the private members of your superclass or else they wont be private. you can have protected or public accessor methods in superclass and that could return the value of your private variables. OR, you could use reflection to access the private variables. But that you could use for anything, not only just superclass.
you can not access private variables outside of the class.
to access them,
1. you may make them public or protected but it is not a good idea.
2. you can write getter method for it which is again not a private method,It is good approach.
3. you may use reflection to access it.
provide more information to help you better
It depends on what language you are using. If you are using C++, you may be able to make the sub-class a friend of the super-class and then you could access its public members. If you you use Java, you could use reflection to locate the super object and reflect on that, but it would be more trouble than it would be worth.