I Have this class:
public abstract class Test {
public abstract class SubClass extends Test
{
}
}
I need to access it like this
public class JavaApplication1 extends Test.SubClass {
public JavaApplication1()
{
super();
}
}
But having problem with super.
I Cant use it static nor extend Test
What should I do?
Thanks in advance
One solution: make SubClass a static inner class.
Another possible solution:
public class JavaApplication1 extends Test.SubClass {
public JavaApplication1() {
new Test() {}.super();
}
public static void main(String[] args) {
new JavaApplication1();
}
}
abstract class Test {
public Test() {
System.out.println("from Test");
}
public abstract class SubClass extends Test {
public SubClass() {
System.out.println("from SubClass");
}
}
}
Which returns:
from Test
from Test
from SubClass
Why are you extending an inner class from the outside of the class containing it? Inner class should be used only when you need a specific need inside a Class. If there are more classes that could benefit from the services offered by a Class then it shouldn't be inner but a top level class.
The problem is accessing an inner class needs an instance of the outer class. So, you can't directly invoke super() from your JavaApplication1 constructor. The closest you can get is by creating a 1-arg constructor, passing the instance of the outer class, and then invoke super on that instance: -
public JavaApplication1(Test test)
{
test.super();
}
And then invoke the constructor as: -
new JavaApplication1(new Test() {});
This will work fine. But, with 0-arg constructor, you would have to create an instance of Test class first (in this case, an anonymous inner class, since Test is abstract), and then invoke super().
public JavaApplication1() {
new Test() {}.super();
}
Related
Example abstract class is bellow.
public abstract class Vehicle {
void maintain(String str) {
System.out.println(str);
}
}
Example concrete class is bellow.
public class Driver {
public static void main(String[] args) {
}
}
Now I need to access the maintain method without extending the Vehicle class.Is there any way to do this without using static content?
No, there isn't, because maintain is an instance method. To call an instance method, you must have an instance. You can't create an instance of an abstract class.
You can subclass it anonymously (see this tutorial), but you still need to subclass it.
You can use an anonymous inner class. I've used your example code but also defined an anstract method in Vehicle
public class AbstractTest {
public static void main(String[] args){
Vehicle v = new Vehicle() {
#Override
void myOtherAbstractMethod() {
// Do what you need here
}
};
v.maintain("foo");
}
public static abstract class Vehicle {
void maintain(String str) {
System.out.println(str);
}
abstract void myOtherAbstractMethod();
}
}
You cannot do that as abstract classes are abstract. Also in your case there's no connection between Driver and Vehicle so even if you would be able to compile that code (you won't), then ClassCastException would show up.
You must extend abstract class first, like it or not.
I have the below two classes. I'm wondering how I'm able to call the instance method of ClassA i.e. AMessage() in class B with out the instance of a ClassA or ClassB created?
I was thinking I should call instance method of ClassA i.e. AMessage() in class B as below:
new ClassA().AMessage(); //no compile error
new ClassB().Amessage(); //no compile error
Parent Class (ClassA.java)
public class ClassA {
public void AMessage(){
System.out.println("A Message");
}
}
Child Class (ClassB.java)
public class ClassB extends ClassA{
public void BMessage(){
AMessage(); //no compile error
}
public static void main(String[] args){
new ClassB().BMessage();
}
}
When a class extends another class, it automatically inherits the visible fields and methods of the base class. By visible I mean accessible members. Private members are not inherited. Learn more about inheritance in http://www.tutorialspoint.com/java/java_inheritance.htm
So if you have a class ClassA having a method AMessage like this :
public class ClassA{
public void AMessage(){
System.out.println("A message");
}
}
and ClassB which extends ClassA like this :
public class ClassB extends ClassA{
public void BMessage(){
AMessage();
}
public static void main(String[] args){
new ClassB().BMessage();
}
}
ClassB automatically inherits members of ClassA i.e. they act as if they are members of ClassB itself. That's why we can call the instance method of ClassA inside ClassB without any instance, because they belong to ClassB as well. Also besides instance methods, you can call static methods like that as well. (But of course you can not call instance methods inside static methods.)
As an additional answer I would like to suggest that (although it is not related to the question but it is a good practice) you should not name any method of a class (instance or static) starting with a capital letter. It doesn't generate any compiler error if you still name it like that, but it affects the readability. I have written the names like that only to relate to your question.
Use super keyword to call base class methods. Check this for reference -
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
public class ChildClass extends BaseClass{
public static void main(String[] args){
ChildClass obj = new ChildClass();
obj.Message();
}
public void Message(){
super.Message();
}
}
class BaseClass {
public void Message(){
System.out.println("Base Class called");
}
}
Or you can do it like this as well -
public class ChildClass extends BaseClass{
public static void main(String[] args){
new ChildClass().Message();
}
}
class BaseClass {
public void Message(){
System.out.println("Base Class called");
}
}
yes you can call method directly instance method of parent class from child class object provided parent class method should be public
you can call in this way
new ClassB().AMessage();
it will also work
Wat does it mean by indirect Instantiation of abstract class ? how do
we achieve this ?
as i tried few times like .. it gives error has any one done something regarding this
abstract class hello //abstract class declaration
{
void leo() {}
}
abstract class test {} //2'nd abstract class
class dudu { //main class
public static void main(String args[])
{
hello d = new test() ; // tried here
}
}
We can't instantiate an abstract class .If we want than we have to extend it.
You can't instantiate an abstract class. The whole idea of Abstract class is to declare something which is common among subclasses and then extend it.
public abstract class Human {
// This class can't be instantiated, there can't be an object called Human
}
public Male extends Human {
// This class can be instantiated, getting common features through extension from Human class
}
public Female extends Human {
// This class can be instantiated, getting common features through extension from Human class
}
For more: http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Wat does it mean my indirect instanciation of abstract class ? how do we achieve this ?
I'd need to see the context in which that phrase is used, but I expect that "indirect instantiation" means instantiation of a non-abstract class that extends your abstract class.
For example
public abstract class A {
private int a;
public A(int a) {
this.a = a;
}
...
}
public B extends A {
public B() {
super(42);
}
...
}
B b = new B(); // This is an indirect instantiation of A
// (sort of ....)
A a = new A(99); // This is a compilation error. You cannot
// instantiate an abstract class directly.
You can't create instance of abstract class, I think this is what you are trying to do.
abstract class hello //abstract class declaration
{
void leo() {}
}
class test extends hello
{
void leo() {} // Custom test's implementation of leo method
}
you cannot create object for Abstract class in java.
Refer this link-http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
I had a doubt.
Imagine If we have a class A that implements the method
For example
private void methodA(int index) throws Exception, Error {
}
And if we have a Class B that extends the first class A.
My questions is, can class B implement
private void methodA(int index) throws Exception, Error {
}
And which method will be called under which circumstance!!
Thanks
If your methods weren't declared "private", this would just be standard polymorphism. Because they're private, the rules are a bit different. The version in class A can only be called from code that's in class A. The version in class B can only be called from code that's actually written in class B (as opposed to code that class B gets by extending class A).
YES, you can implement the methodA method in class B, but, pay attention, you are not overriding it.
Your method is declared ad private so is not "visible" from extending classes.
If your intention is to make your method overridable, you need to declare it as public.
Just give it a try :)
public class Main {
public static void main(String[] args) {
Base base;
base = new A();
System.out.println(base.doSth());
base = new B();
System.out.println(base.doSth());
}
}
abstract class Base {
public abstract String doSth();
}
class A extends Base {
#Override
public String doSth() {
return "A";
}
}
class B extends A {
#Override
public String doSth() {
return "B";
}
}
I think you wonna override the super-class method, and to do this, the method on sub-class must have the same signature of super-class method.
You can call these methods in following ways:
Suppose test1 is an instance of classA, teste1.methodA(index) will execute the implementation on super-class.
Suppose test2 is an instance of classB, test2.methodA(index) will execute the sub-class method.
In classB you can invoque the super class method (if the method is notprivate), something like :
public class ClassB extends ClassA
{
...
super.methodA(index);
...
}
Hi i have a Base class containing one string member as belows :
public class BaseClass
{
public String test;
}
Child class extending base class where i wish to initialize the test value.
public class ChildClass extends BaseClass
{
public void initialize()
{
System.out.println("inside constructor of ChildClass.");
this.test="stringtest";
}
}
Test class where i wish to use the value of test variable of base class:
public class TestClass extends BaseClass
{
public void test()
{
new ChildClass().initialize();
System.out.println(this.test);
}
public static void main(String[] args) {
new TestClass().test();
}
}
Now my above code is printing null inside test class. why so? although i have initialized the test variable in child class? am i going wrong somewhere in java concepts?
the problem is that you create new ChildClass but you aren't setting it in a variable. then you print this.test which is never set.
when you are in test method you are in TestClass instance:
you are creating and setting a ChildClass class
but then you are printing the TestClass test member
if you just want to create ChildClass and use it do
public class TestClass
{
public void test()
{
ChildClass cls =new ChildClass().initialize();
System.out.println(cls.test);
}
public static void main(String[] args) {
new TestClass().test();
}
}
or if you want to extend ChildClass do
public class TestClass extends BaseClass
{
public void test()
{
initialize();
System.out.println(this.test);
}
public static void main(String[] args) {
new TestClass().test();
}
}
new ChildClass() and new TestClass() are 2 different objects even if they are extending common BaseClass.
Having a common BaseClass as super class doesn't mean that it shares the non static fields of it, with all the instances of its different subclasses
This would have worked if test was static (shared class field) in BaseClass
There are two instances of BaseClass in the example you posted. One is the one instantiated with new ChildClass() and the other one is instantiated by the main() method (TestClass). Each one of them, being a subclass of BaseClass, has its own test member (they are different variables with different values).
Remember that the this keyword always references the instance in which it is used.
In this case, System.out.println(this.test); is accessing the test property of the TestClass instance created in the main method.
You need to access the test property of the other instance. You could do so by keeping a reference to the ChildClass instance and accessing the test property afterwards:
ChildClass instance = new ChildClass().initialize();
System.out.println(instance.test);
You might find the following Java Tutorials page useful: Using the this Keyword.
Also take into account that TestClass doesn't need at all to extend BaseClass. You could keep accessing instance.test because it is a public member, but you should consider making the field private and provide getter and setter methods. See the following question for relevant information on this: Why use getters and setters?
You need a instance of Child Class
ChildClass cls =new ChildClass().initialize();
System.out.println(cls.test);
this is referring to the Test Class instance.