首页 > 解决方案 > 为什么 Java 对象在 Java 继承中产生不同的输出?

问题描述

class Book {
    int op,mp;
    String name,auther;
    void Setdata(String n,String au)
    {
        name=n;
        auther=au;

    }
    void Display()
    {
        System.out.println("Name:"+name);
        System.out.println("Auther:"+auther);
        System.out.println("Ocford price: "+op);
        System.out.println("MC price: "+mp);
    }

}
class Oxford extends Book
{
    void price(int p)
    {
        super.op=p;
    }
}
class Mc extends Book
{
    void price(int p)
    {
        super.mp=p;
    }
}
public class Sai
{
    public static void main(String args[])
    {
        Oxford o=new Oxford();
        Mc m=new Mc();
        Book b=new Book();
        b.Setdata("Java","Robert");
        o.price(300);
        m.price(400);
        b.Display();
    }
}

我的输出:

预期输出:

为什么两个类的对象(Oxford,Mc 由 book 类扩展)不能为 book 的类变量赋值。打印预期输出的解决方案是什么。

标签: javaobjectinheritance

解决方案


它不是对象和继承的工作方式。

您需要学习静态变量和非静态变量。

静态变量:-

它是类级别的变量,可以访问同一类或继承类的所有对象。

非静态变量:-

它的范围是对象级别。意味着每个对象都有自己的变量副本。就像如果有一个变量 int a = 10; 那么每个对象都有一个 a 的副本。如果您更改 1 个对象的值,它不会更改另一个对象的值。

现在来到你的代码你犯了一些错误。将您的代码与以下代码进行比较。我也会评论每一行,我会改变。

class Book {
    int op,mp;
    String name,auther;
    void Setdata(String n,String au)
    {
        name=n;
        auther=au;

    }
    void Display()
    {
        System.out.println("Name:"+name);
        System.out.println("Auther:"+auther);
        System.out.println("Ocford price: "+op);
        System.out.println("MC price: "+mp);
    }

}
class Oxford extends Book
{
    void price(int p)
    {
        super.op=p;
    }
}
class Mc extends Oxford  // If you want to set all price for same book and aurthor
{
    void price(int p)
    {
        super.mp=p;
    }
}
public class Sai
{
    public static void main(String args[])
    {


        Book b=new Mc(); // also you can define it as Mc b=new Mc(); but its advised to define object as generalize as possible.(another whole topic )

        b.Setdata("Java","Robert");
        b.price(300);
        b.price(400);
        b.Display();
    }
}

它会给你想要的输出。


推荐阅读