java - 为什么 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();
}
}
我的输出:
- 名称:Java
- 作者:罗伯特
- 牛津价格:0
- 麦克价格:0
预期输出:
- 名称:Java
- 作者:罗伯特
- 牛津价格:300
- mc价格:400
为什么两个类的对象(Oxford,Mc 由 book 类扩展)不能为 book 的类变量赋值。打印预期输出的解决方案是什么。
解决方案
它不是对象和继承的工作方式。
您需要学习静态变量和非静态变量。
静态变量:-
它是类级别的变量,可以访问同一类或继承类的所有对象。
非静态变量:-
它的范围是对象级别。意味着每个对象都有自己的变量副本。就像如果有一个变量 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();
}
}
它会给你想要的输出。
推荐阅读
- python - Keras:使用 model.fit() 洗牌数据不会做出改变,但 sklearn.train_test_split() 会
- javascript - 仅在单击按钮时可视化传单地图
- python - 如何对包含列表的列进行分组
- python-3.x - 转换卷曲请求
- javascript - 在 HTML 中的函数名之后定义索引时,设置 timeout() 方法不起作用?
- python - 使用 Django 在 PostgreSQL 中查询 jsonb 字段:IN vs. CONTAINS
- c++ - 如何结合使用thrust和valgrind来检测内存泄漏?
- html - HTML/CSS:如何在两个浮动段落之间添加空白?
- dart - 无法从命令行创建基本骨架 [dart]
- php - 表没有输出到我的 plan.php 网页