I have three classes, and I need to modify first class through the second that is extended :
my first class A :
public class A{
private String name;
public void setName(String name) {
this.name= name;
}
my second class B
public abstract class B {
public void init() {
A a = new A();
a.setHost("foo");
}
}
my third class C
public class C extends B {
// I want to use the method setName() of the a declared in class B
b.init.a.setName("bar");//compile error, I tried several syntax I don't know how to do it
}
expected output, in my third class :
a.Getname = "bar"
Your code has multiple issues:
1) Variable b is never declared.
2) Variable a is private to method init, so you can't access it outside the init method.
So the solution should be like:
Class B:
public abstract class B {
protected static A a = new A(); // Protected to make it visible to child class
public void init() {
a.setHost("foo");
}
}
Class C:
public class C extends B {
public static void main(String[] args) {
a.setName("bar");
System.out.println(a.getName()); //Output = bar
}
}
you can return a in the init method of B like below.
public A init() {
A a = new A();
a.setHost("foo");
return a;
}
Then you can set the value in C like below
public class C extends B {
public setNameinA() {
B b = new B();
b.init().setName("bar");
}
}
Trying to add a base interface with method so all derived classes have to implement the method or use default method. What's the best way to going about getting this method callable? See comment in code block below.
public interface IA{}
public interface IB{
public Integer doWork();
}
public interface IC extends IB{
}
class B implements IB{
Integer doWork(){
return 2;
}
}
class C extends B implements IC{
#Override
Integer doWork(){
return 7;
}
}
//What do I need to do to cast clazz to an object so I can call the derived class' doWork method?
private Integer newClient(Class<T> clazz){
((B) clazz).doWork();
}
Ended up finding a solution:
B.class.cast(clazz);
As for how to ensure you call the derived class' method that overrides the base, that is a native behavior of Java.
Example Program:
public class Foo {
static class A {
int get() { return 0; }
}
static class B extends A {
#Override
int get() { return 1; }
}
public static void main(final String[] args)
{
A a = new A();
B b1 = new B();
A b2 = new B();
printA(a);
printA(b1);
printA(b2);
}
public static <T extends A> void printA(T bObj) {
System.out.println(bObj.get());
}
}
Output:
0
1
1
Note that the output returned from b2::get()::int is the same as b1::get()::int, even though b2 is type A and b1 is type B. This is because even though we only have a reference to the A class in b2, the object implementation is still B.
It seems that you only want to know how to instantiate the Class. Assuming it has a default constructor you can do it this way:
private Integer newClient(Class<B> clazz){
try {
((B) (clazz.getConstructor().newInstance())).doWork();
} catch ...
}
I have two Java classes, one of which inherits from other. They are somewhat like the following:
A.java:
public class A {
public String invocations[] = {"foo"};
public A() {
// do stuff
}
}
B.java:
public class B extends A {
public String invocations = {"bar", "baz"};
public B() {
super();
}
}
In this example, assuming I create an instance of B and get its invocations property, it returns {"foo"} instead of the expected {"bar", "baz"}. Why is this, and how can I get the {"bar", "baz"}?
You have one variable hiding another one. You can refer to a variable in a super class by using a cast to the type explicitly. (I am assuming you fix the syntax errors)
public class Main {
static class A {
public String[] invocations = {"foo"};
}
static class B extends A {
public String[] invocations = {"bar", "baz"};
}
public static void main(String... args) {
B b = new B();
System.out.println("((A)b).invocations=" + Arrays.toString(((A) b).invocations));
System.out.println("b.invocations=" + Arrays.toString(b.invocations));
}
}
prints
((A)b).invocations=[foo]
b.invocations=[bar, baz]
if I have an abstract class and a class that extends it, how can I get variable of the class that extends it to the class that is extended, something like this:
abstract class A {
void getVariable () {
//get *variable* from class B and print it out
}
}
class B extends A {
int variable = 5;
}
You cannot access variable field from child class directly but you can do like this
abstract class A {
abstract int getVariable ();
void anotherMethod() {
System.out.println("Variable from child: " + getVariable());
}
}
class B extends A {
int variable = 5;
#Override
int getVariable() {
return variable;
}
}
Forget about variables: What you might inherit and override is behaviours (=methods). Try this:
abstract class A {
protected abstract int getVariable ();
}
class B extends A {
private int variable = 5;
protected int getVariable ()
{
return variable;
}
}
class C extends A {
protected int getVariable ()
{
return 0; // This class might decide not to define its own variable.
}
}
variable is only known to class B. Its superclass A has no knowledge of it. If you move variable to the superclass A and don't mark it private, then you can access it from B.
Below is the example for Inheritance
class Parent {
Parent(int a, int b) {
int c = a + b;
System.out.println("Sum=" + c);
}
void display() {
System.out.println("Return Statement");
}
}
class Child extends Parent {
Child(int a, int b) {
int c = a - b;
System.out.println("Difference=" + c);
}
}
public class InheritanceExample {
public static void main(String args[]) {
Child c = new Child(2, 1);
c.display();
}
}
I get the below error when I don't have the non-parametrized constructor parent()
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor
at Child.<init>(InheritanceExample.java:14)
at InheritanceExample.main(InheritanceExample.java:22)
Can you please explain me what is the purpose of the constructor without parameters in base class.
class child extends parent
{
child(int a,int b)
{
int c=a-b;
System.out.println("Difference="+c);
}
}
The first thing the child class constructor must do is call the parent class constructor.
If you do not do this explicitly (e.g. super(a,b)), a call to the default constructor is implied (super()).
For this to work, you must have this default constructor (without any parameters).
If you do not declare any constructors, you get the default constructor. If you declare at least one constructor, you do not get the default constructor automatically, but you can add it again.
The error message you are getting is complaining about the implied call to super() not working, because there is no such constructor in the parent class.
Two ways to fix it:
add a default constructor
in the first line of the child constructor, call a non-default parent constructor (super(a,b))
Also, please don't use all-lowercase class names.
The reason it is asking for parent() is because child extends parent, but you do not explicitly call super(a,b) in the child constructor. Since there is no explicit call to the parent constructor, javac tries to call the default constructor parent() and complains when it can't find it.
You can see this with this code:
class parent
{
public parent() {
System.out.println("Parent Constructor");
}
public parent(int a,int b) {
int c=a+b;
System.out.println("Sum="+c);
}
public void display() {
System.out.println("Return Statement");
}
}
class child extends parent
{
public child(int a,int b) {
int c=a-b;
System.out.println("Difference="+c);
}
}
public class InheritanceExample
{
public static void main(String args[]) {
child c=new child(2,1);
c.display();
}
}
Output:
Parent Constructor
Difference=1
Return Statement
Also, this works fine with no default constructor:
class parent
{
public parent(int a,int b) {
int c=a+b;
System.out.println("Sum="+c);
}
public void display() {
System.out.println("Return Statement");
}
}
class child extends parent
{
public child(int a,int b) {
super(a,b);
int c=a-b;
System.out.println("Difference="+c);
}
}
public class InheritanceExample
{
public static void main(String args[]) {
child c=new child(2,1);
c.display();
}
}
Output:
Sum=3
Difference=1
Return Statement
I think there was a similar question at:
Why should the derived class constructor always access base class constructor?
You can think of it this way: since "child" inherits from "parent", "child" must also be a valid instance of "parent" (polymorphism) before it can behave as a "parent" itself. As such, the very first thing "child" must do is construct itself as a valid "parent" - so a call to "parent"'s constructor via super() must be the first method call in the constructor. If no such call is present, an implicit call to the no-parameter constructor of "parent" results.
The error is there for the reason that if we do not call super explicitly then JVM puts super() in the constructor of the child class and this super() searches a constructor in parent class without parameter which is not in your class so it is wrong. Either put a non parametrised constructor in parent class or put the statement super(a,b) in the very first line of the child constructor.
class Parent
{
Parent(int a, int b)
{
int c = a + b;
System.out.println("Sum=" + c);
}
void display()
{
System.out.println("Return Statement");
}
}
class Child extends Parent
{
Child(int a, int b)
{
super(a,b);
int c = a - b;
System.out.println("Difference=" + c);
}
}
class InheritanceExample
{
public static void main(String args[])
{
Child c = new Child(2, 1);
c.display();
}
}
public class Mobile{
private String manufacturer;
private String operating_system;
public String model;
private int cost;
Mobile(String man, String o,String m, int c){
this.manufacturer=man;
this.operating_system=o;
this.model=m;
this.cost=c;
}
public String getModel(){
return this.model;
}
}
public class Android extends Mobile{
Android(String man, String o,String m, int c){
super(man,o,m,c);
}
public String getModel(){
return "This is Android mobile" +model;
}
import java.io.*;
public class XXX
{
public static void main()throws IOException
{
System.out.println("Enter your name.");
String name = in.readLine();
System.out.println(name+" rules!! Thank You!!");
}
}