How to call a parameterised constructor present in a base class? - java

Iam beginner in programming iam struct at how to call parameterised constructor presented in base class.
My code:
public class base {
int a, b;
base(int x) {
a = x;
System.out.println(a);
}
static class derived extends base {
derived(int y) {
b = y;
System.out.println(b);
}
}
public static void main(String[] args) {
derived de = new derived(10);
}
}

super(int) refers to base(int x):
derived(int y) {
super(DEFAULT_VALUE_FOR_A);
b = y;
System.out.println(b);
}
where DEFAULT_VALUE_FOR_A is an int value to initialise the field a from base.
Please, follow the Java naming convention, your code is hard to read. The first letter of the class name should be capitalized.

When ever you creates object of any class constructor of parent is also called
In your case derived de = new derived(10); Will call base() in derived(int y) ..
Either add default constructor in base class or call parametarized constructor form base
public class Base {
int a, b;
Base(){} // if you remove this please add super(0) in Derived(int y)
Base(int x) {
a = x;
System.out.println(a);
}
static class Derived extends Base {
Derived(int y) {
// super(0); // uncomment this if you dont want to add default constructor in your parent class
b = y;
System.out.println(b);
}
}
public static void main(String[] args) {
Derived de = new Derived(10);
}
}

Related

How to create constructor for a subclass

import java.util.*;
class A {
protected int n;
public A(int a) {
n = a;
}
protected int disp() {
return n;
}
}
class B extends A {
// what should i do here
}
public class Hello {
public static void main(String[] args) {
//Your Code Here
int a =5;
A obj= new B(a);
System.out.print(obj.disp());
}
}
What is important is that A is initialized using one of its consutructors. It is not necessary that the constructor in child class B match the parameters of the constructor(s) in A. Hence, you may define any constructor in the child class B but make sure that you call super( <some int> ) in that.
Eg, even the following is fine.
class B extends A {
public B(){ //Default constructor
super( 1 );
}
}
Also,
If you have more than one constructor in child class B, then each of them must call super( <some int> ).
If you have more than one constructor in parent class A, then in the child class constructor, calling any one of them through super( <params> ) will do.
You should do the following in B class:
class B extends A {
public B(final int a) {
super(a);
}
}
What happen here is that we're calling the constructor of our parent (A)

Method overloading with float and double type in super class and base class

Why float method is not considered of Derive class in below program?
In the below program when I assign derive object to base class at that time base.f(20) consider the Derive class int method but base.f(20.0f) is not considered Derive class float method.
Can you guys explain me what is the logic behind this?
public class Tricky3 {
public static void main(String[] args) {
Derive derive = new Derive();
System.out.println(derive.f(10));
System.out.println(derive.f(10.0f));
System.out.println("------------------New Logic-----------------");
Base base = new Derive();
System.out.println(base.f(20));
System.out.println(base.f(20.0f));
}
}
class Base {
public int f(int i) {
System.out.print("Base f (int): ");
return i + 3;
}
public double f(double i) {
System.out.print("Base f (double) : ");
return i + 3.3;
}
}
class Derive extends Base{
public float f(float i) {
System.out.print("Derive f (float) : ");
return i + 3.3f;
}
public int f(int i) {
System.out.print("Derive f (int): ");
return i + 3;
}
}
Output
Derive f (int): 13
Derive f (float) : 13.3
------------------New Logic-----------------
Derive f (int): 23
Base f (double) : 23.3
You are using Base base reference variable and Derive derive object.
base.f(20.0f) will try to find Base.f(float)method signature, when it cannot find Base.f(float) the Dynamic Binding with Derive.f(float) cannot happen, then it will search for closest method which can support base.f(20.0f) call which is Base.f(double).
If you declare f(float) in Base class then Dynamic Binding will happen and Derive.f(float)
will be called.
When you choose to declare a style
Parent p = new Child();
You are accessing members from parent and implementations from children execute runtime. Since your parent doesn't have method with float type it chosen from Base. If you override the same method in children, that executes.
The problem can be reduced to the following snippet:
class Base {
public double f(double x) {
System.out.println("Base.f");
return x;
}
}
class Derived extends Base {
public float f(float x) {
System.out.println("Derived.f");
return x;
}
}
public class Main {
public static void main(String[] args) {
new Derived().f(1.0f); // Derived.f
( (Base)new Derived() ).f(1.0f); // Base.f
}
}
When evaluating new Derived().f(1.0f) the compiler has the choice
to implicitly convert the float parameter into a double and call Base.f(double), or
to call Derived.f(float) without conversion.
The compiler chooses the Derived.f(float) overload because it manages without conversion.
When evaluating ( (Base)new Derived() ).f(1.0f) the compiler no longer knows about the Derived.f(float) overload and is forced to do the conversion and then call Base.f(double).
The behavior would be different if Derived.f and Base.f had the same signature. Then the method would be overwritten and both statements would call Derived.f:
class Base {
public double f(double x) {
System.out.println("Base.f");
return x;
}
}
class Derived extends Base {
public double f(double x) {
System.out.println("Derived.f");
return x;
}
}
public class Main {
public static void main(String[] args) {
new Derived().f(1.0f); // Derived.f
( (Base)new Derived() ).f(1.0f); // Derived.f
}
}

inheritance and protected class java

error: mul(int,int) has protected access in Multiplication
Thoughts on what I'm doing wrong?
public class Multiplication{
protected int mul(int a,int b){
return (a*b);
}
}
class ImplimentPkg extends Multiplication {
public static void main(String args[]){
Multiplication obj=new ImplimentPkg();
//Here's the error
System.out.println(obj.mul(2,4));
}
protected int mul(int a,int b){
System.out.println("");
return 0;
}
}
Java tutorial says:
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
You may think you have matched the second case(inheritence).
Multiplication obj = new ImplimentPkg();
System.out.println(obj.mul(2, 4));
This means you are using an instance of parent class Multiplication. Although the code is inside a method of subclass of Multiplication. It doesn't mean the instance obj has something to do with inheritance. And of course the mul(...) method is invisible. What you can do is: use keyword super.
public void bar() {
Multiplication mul = new Multiplication();
mul.mul(1, 2); // <- error
super.mul(1, 2); // correct
Multiplication.foo(); // correct
}
Note: if you have protected static method in parent class, like:
public class Multiplication {
private String name = "some";
protected int mul(int a, int b) {
return (a * b);
}
protected static void foo() {
System.out.println("foo");
}
}
Here the foo() method can be accessed everywhere in subclass, but not other classes. By the way, you shouldn't use protected static method, see reasons here.
Another related topic may be interested to you, see here.
Create each class in its own Java file
ImplimentPkg.java
package my;
class ImplimentPkg extends Multiplication {
public static void main(String args[]) {
Multiplication obj = new ImplimentPkg();
System.out.println(obj.mul(2, 4));
}
protected int mul(int a, int b) {
System.out.println("");
return 0;
}
}
Multiplication.java
package my;
public class Multiplication {
protected int mul(int a, int b) {
return (a * b);
}
}

How come variables are initialized to their default values even if we have a constructor

i have a question regarding default constructors in java.
as much as i have read about constructors in java, a default constructor initializes all instance variables to their default values. but what if we define a constructor for a class, then how come variables are initialized to their default values if we want them to ?
suppose i have 2 files
a.java
public class a
{
int x;
public a(int z)
{
if(z > 0)
{
x = z;
}
}
public void get()
{
System.out.println(x);
}
}
and b.java
public class b
{
public static void main(String[] args)
{
a obj = new a(-4);
obj.get();
}
}
now here condition (z>0) fails, so x is initialized to zero. but what exactly does this as their is no default constructor in class a.
Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.
Source
That means that the compiler will do that for you when you build the program.
In your a class (renamed A below to follow conventions) as you have written it, there is no default constructor. A default constructor for a class is a constructor which is public and has no arguments.
With the code you have written, this will fail:
A a = new A();
As soon as you declare another constructor in a class, there is no default constructor anymore.
As to instance variables, if you do not initialize them explicitly, they are set to default values. That is:
public class A
{
private int x;
public int getX()
{
return x;
}
}
if you do:
final A a = new A();
System.out.println(a.getX());
this will print out 0. The class above is exactly equivalent to:
public class A
{
private int x /* = 0 -- default value for uninitialized int instance variables */;
// redundant
public A()
{
}
public int getX()
{
return x;
}
}
When you declare a variable in java, it's by default initialized as it's default value.
For the primitive types is that 0 (or it's equivalent), for Objects is that null
So in your example has x initialy the value 0 and you never overwrite it.
In java if we dont define any constructor, it takes its self a default constructor which will have default values.while we creating object we intialize values to the constructor.
public class Car{
int numOfWheels;
public Car(int numOfWheels){ //created constructor//
this.numOfWheels=numOfwheels;
}
}
public static void main(string[]args){
Car skoda = new Car(4);
} *//initialized value to the object using constructor in parenthesis//*
public class a
{
int x;
public a(int z)
{
//as we know that every class base class is Object class this constructor first statement is super(); means compiler automatically add this statement that call object class default constructor and initialize default values
if(z > 0)
{
x = z;
}
}
public void get()
{
System.out.println(x);
}
}
public class a
{
int x;
public a(int z)
{
/*As we know that every class base class is Object.....
compiler automatically add super(); that call Object class default constructor
that initialize the value of instance variable */
if(z > 0)
{
x = z;
}
}
public void get()
{
System.out.println(x);
}
}
public class b
{
public static void main(String[] args)
{
a obj = new a(-4);
obj.get();
}
}
//other example is below
/*class A
{
public A()
{
System.out.println("Arjun Singh Rawat and Ashish Chinaliya");
}
}
class B extends A
{
public B()
{
//compiler automatically add super();
}
}
class calling
{
public static void main(String arg[])
{
B bb=new B();
}
}*/
thanks...
public class Demo {
static int a;
Demo(int b )
{
System.out.println(" Constructor");
}
public static int func()
{
System.out.println(a);
return 1;
}
public static void main( String args[])
{
new Demo(func());
}
}
Output
0
Constructor
It's not the default constructor that initializes our fields to their default values ,
In this program, the static field a is being initialized to 0 even though there is no default constructor
added by the compiler. Also it's being initialized to 0 before a constructor being called .

get super class value in java

I have 2 classes:
public class A
{
int n = 10;
public int getN()
{
return n;
}
}
public class B extends A
{
int n = 20;
public int getN()
{
return n;
}
}
public class Test
{
public static void main(String[] args)
{
B b = new B();
System.out.println(b.getN()); //--> return 20
System.out.println(((A)b).getN()); //--> still return 20.
//How can I make it return 10?
}
}
All methods in Java are always virtual. That is, there is no way of invoking the "super"-version of the method from the outside. Casting to A won't help as it doesn't change the runtime type of the object.
This is probably your best alternative / workaround:
class A {
int n = 10;
public int getN() {
return n;
}
public final int getSuperN() { // "final" to make sure it's not overridden
return n;
}
}
class B extends A {
int n = 20;
public int getN() {
return n;
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
System.out.println(b.getN()); // --> return 20
System.out.println(((A)b).getN()); // --> still return 20.
System.out.println(b.getSuperN()); // --> prints 10
}
}
you can't make the value be "10" because the instance of the object was for class B, and when you do the cast the only thing that are you doing is changing the define class not setting values for the object B, in other words if you need to get 10 its' something like this
b = new A();
That thing won't work due to polymorphism. Class B is still class B even if you cast it into its super class.
I think you'll need something like this:
public class B extends A
{
int n = 20;
/**
* #return the super n
*/
public int getSuperN()
{
return super.n;
}
}
What you see is polymorphism in action. Since b is a B, that method (which returns 20) is always called (regardless if you cast it to an A).

Categories