使用子类实例访问父类被重写的方法

OC中继承子类对象调用方法机制 子类对象访问父类中的实例变量 在继承中,子类对象如何调用 阅读详情

最近看文章时候遇到一个问题,怎么使用子类实例访问父类被重写的方法,一直百度也没看到啥答案,问题如下所示:
定义了一个Circle类,提供了一个area()方法得到其圆的面积,有一个Cylinder 类继承了Circle类,它重写了父类之中的area(),返回的是圆柱的表面积。现在需要通过一个Cylinder 类的对象来获得他的底面圆面积,即调用父类中被重写的area()方法。
首先我想到的是通过强制类型转换,将Cylinder类的对象转换为Circle,即((Circle)cy1).area(),但是运行的结果其调用的还是子类中的area()方法。可能是编译器的运行时类型还是Cylinder 类型,自动调用了area()方法。

public class Test {
    public static void main(String[] args) throws Exception {
        Cylinder cy1 = new Cylinder(5, 20);
        Cylinder cy2 = new Cylinder(10, 20);
        System.out.println("cy1 的底圆面积为" + ((Circle)cy1).area() + "; 周长为" + ((Circle)cy1).perimeter());
        System.out.println("cy1 的表面积为" + cy1.area() + "; 体积为" + cy1.volume());
        System.out.println("cy2 的底圆面积为" + ((Circle)cy2).area() + "; 周长为" + ((Circle)cy2).perimeter());
        System.out.println("cy2 的表面积为" + cy2.area() + "; 体积为" + cy2.volume());

    }
}
interface Shape{
    double PI = Math.PI;
    double area();
}
class Circle implements Shape{
    public double radius;

    public Circle(double radius) {
        this.radius = radius;
    }
    @Override
    public double area() {
        return Shape.PI * radius * radius;
    }
    public double perimeter(){
        return 2 * Shape.PI * radius;
    }
}
class Cylinder extends Circle{
    public double height;

    public Cylinder(double radius, double height) {
        super(radius);
        this.height = height;
    }
   @Override
    public double area() {
        return 2 * super.area() + super.perimeter() * height;
    }
    public double superArea(){
        return super.area();
    }

    public double volume(){
        return super.area() * height;
    }
}

–
程序运行的结果为:
运行结果
可以看到,底圆面积与表面积相同,即调用了还是子类中的area()。
最后,我想通过反射,重新创造一个父类的实例来解决问题。
((Circle)cy1.getClass().getSuperclass().getDeclaredConstructor(double.class).newInstance(cy1.radius)).area()
即
修改后的demo
通过cy1对象,获得它的父类class对象,通过getDeclaredConstructor()方法,获得有参构造器,然后创建一个父类的实例,传入cy1.radius作为参数,再用该对象调用area()方法,最终成功调用到父类的area()方法。
运行结果:
修改demo后的结果
当然更简单的做法是,在子类中再创建一个方法superArea(),其直接用super关键字直接调用父类的area()方法,即super.area(),通过cy1对象调用superArea()就可以得到结果
demo:

public double superArea(){
        return super.area();
    }
    
java继承中关于继承的特殊注意事项:引用类型为父类,但实例化为子类对象时调用变量或方法的结果分析 关于继承的特殊注意事项: package defaul; class f{ int x,y; f(int x,int y){ this.x=x; this.y=y; } int num = 12; void eat(){ System.out.println("父类里的吃方法"); } } class z extends f{ z(... 阅读详情

相关推荐

C#中方法的重写(实现多态)

前言 问题1:什么时候要重写方法? 当子类继承父类时,子类中方法名称与父类中方法名称重名时,需要让父类的方法变成虚方法;让子类方法进行重写。 问题2:什么是重写? 对原有基础上的方法需要进行改变。 ...

Nikita 3319

子类继承父类的虚函数调用

子类继承父类中,虚函数再构造函数中和不再构造函数中的调用

u012273328的博客 2万+

open-mmlab / mmpose安装、使用教程

mmpose安装、使用教程mmpose安装教程1. 安装mmcv-full2. 安装MMPose2. 安装mmdet使用教程1. 预测图片2. 预测视频 mmpose mmpose是商汤旗下有又一款好用的工具箱,主要是针对姿态识别任务开发的,包括人体姿态识别和动物姿态识别。里面继承很多现成的网络可以供大家使用,并且提供了训练好的权重。用户可以更具自己的需求训练自己的数据,或者直接应用他们的结果,反正就是很全面啦!!!! github连接:https://github.com/open-mmlab/mmpos

CharmsLUO的博客 1万+

java 通过子类怎么调用父类已经被重写的方法

= =今天看书看到覆盖和重载 我就在想能不能再实例化的子类中调用父类已经被覆盖的方法 百度了很久 除了说super  貌似就不行了   也能在子类中做一个新方法来调用父类已经被覆盖的方法   例如: import java.io.BufferedReader; public class baidu extends Search { public static

f330468286的专栏 1万+

弹簧管压力表设计报告

精密机械课程设计 弹簧管压力表设计报告 2020年5月1日 目 录 第一章 设计任务概述... 3 1.1 课程设计目的... 3 1.2 设计任务... 3 1.3 技术指标... 3 第二章 压力表概述... 4 2.1 机械式压力表的组成部分... 4 2.2 工作原理... 4 第三章 压力表设计... 5 3.1 弹簧管参数设计... 5 3.2 曲柄滑块机构设计... ...

weixin_42163746的博客 6451

用Python实现斗地主游戏(终端版)

马上就要过年了 大家也都放假了吧 过年必不可少的活动 打牌! 今天带大家来写一份斗地主 (又是好多天没怎么更新,忙成狗啊) 那么实现一个斗地主呢 我们肯定要先完善卡牌系统 from collections import Counter import numpy as np import itertools def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def _

Miku_wx的博客 9856

【Java基础】通过子类调用父类被重写的方法

多态 吐槽:既然还要调用父类被重写方法,那为啥还要重写它呢。 使用super关键字可以通过子类调用父类被重写方法。 public class Main { public static void main(String[] args) { Children c = new Children(); c.method(); } } class Father { public void method() { System.out.printl

锥栗的博客 4950

blender中合并的模型,在threejs中显示多个mesh;blender多材质烘培成一个材质

5、优化项(省略此步骤,直接进行步骤6),进入到视图着色方式(此时没有灯光,整体偏暗,如果不调整灯光,烘培出来的材质也偏暗,因此此步骤为优化项,通畅建议调整)。在右边栏进入世界环境,调整颜色。7、烘焙成功之后,新建一个材质,将第三步创建的纹理图像作为材质的纹理,连接到基础色,并把模型的材质改为此材质,其他的材质全部删除。2、处理uv,在侧边栏选择数据-uv贴图,选中使用的uv,进入编辑模式,全选,键盘u,选择智能uv投射。3、处理材质,在侧边栏选择材质,进入着色,在着色器编辑器新建一个图像纹理,新建图像。

AllBluefm的专栏 2529

C++ 子类重写父类函数时调用父类函数方式

子类地址调用相同的父类接口

程序猿的社畜初成长 4392

研制过程评审活动(三)工程研制阶段

工程研制阶段主要任务、及评审活动

Abel的博客 2387

QT+Halcon实现螺纹检测

工业上要检测螺丝的内外直径、内外牙距、内外角度,现在比较好用的图像处理库,开源的opencv,收费的有halcon。为了实现螺纹检测,和对比螺纹检测拿个库比较好。分别用opencv和halcon实现了螺纹检测,通过对比发现用halcon实现的效果比较。现在用博客把实现过程记录下来: 1、需要检测的螺纹数据如下: 2、为了实现检测螺丝以上数据,螺纹内径、螺纹外径、螺纹外牙距、螺纹...

专注现代C++实战,从核心语法到高性能编程,助力开发者深入掌握系统级编程精髓。 7050

【Java】为什么用子类实例化父类,调用父类方法反而会调用子类重写的方法?

案例 class Human{ public void walk() { System.out.println("Human walks."); } } class Man extends Human{ @Override public void walk() { System.out.println("Man walks."); } } class Woman extends Human{ @Override

winrh的博客 1810

以太网MII、RMII、GMII、RGMII(三)

RMII接口收发的数据位宽为2bit,因此管脚数目大为减少,在高密端口PHY中应用较多,但是由于其是MAC和PHY共用一个参考时钟,接口之间的距离不能太远;一般的GMII接口都有两个发送参考时钟:TX_CLK和GTX_CLK,两者的方向是不一样的,前者有PHY提供(同MII),后者由MAC或外部参考时钟源提供,绝大多数GMII接口都是兼容MII接口的,在用作MII模式时,使用TX_CLK和8根数据线中的4根。MII接口中的接收时钟和发送时钟是分开的,而且都是由PHY芯片提供给MAC芯片的。

qq_42357877的博客 2332

重写父类方法、super关键字、调用父类构造器——Java

注:本文参考《疯狂Java讲义》一书 重写父类方法 super 限定 子类调用父类构造器 重写父类方法子类扩展了父类,子类是一个特殊的父类。大部分时候,子类总是以父类为基础,额外增加新的成员变量和方法。但有一种情况例外:子类需要重写父类的方法。例如鸟类都包含了飞翔方法,其中有一种鸟是特殊鸟类——鸵鸟,因此它也会从鸟类获得飞翔方法,但这个飞翔方法明显不适合鸵鸟,所以,鸵鸟需要重写鸟类的方法。我们先看下

Amour 1万+

《网络安全自学教程》- 802.1x协议

802.1x协议架构,工作原理/认证流程,认证方式,MAB认证,触发认证的三种方式,EAP报文格式,EAPOL报文格式

wangyuxiang946的博客 2万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

DAY8重写父类方法&调用父类方法

所谓重写父类方法,就是子类中,有一个和父类相同名字的方法,在子类中的方法会覆盖掉父类中同名的方法。 为什么要重写? 父类的方法已经不满足子类的需要,那么子类就可以重写父类或者完善父类的方法。 示例: 输出结果 实操: 实操 重写成功 如果在Dog中定义一个__init__方法,增加几个实例属性 这样直接运行会报错 理解: 子类并没有定义__init__函数,说明实例化子类的过程中,如果子类没有方法,默认情况下,是调用父类的方法。 在子类中添加一个__init__函数(这也属于重写父类的方法

shanshuyue的博客 2095

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

java子类赋值给父类

package test1;   import java.io.*;   public class demo { publicstatic void main(String[] arg){ Shapes=new Circle(); call(s); }         staticvoid call(Shape s){ s.f1(); s.f2(); s.f3(

a493556721的专栏 4568

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java中父类空间的引用_Java继承关系中,父类方法使用实例变量和调用实例方法的探究...

面向对象编程中,某一个实例方法使用实例变量和调用其它实例方法的情况是常见的。当存在继承关系时,这种情况就变得复杂起来。以下就对继承关系中,父类的某实例方法使用实例变量和其它实例方法的情况进行探究。因为我也是初学者,有理解不到位的地方,还请路过的朋友多多指教。(1)父类实例方法使用实例变量public或protected修饰的实例变量。因为在继承关系中,public和protected修饰的实例变量...

weixin_35045970的博客 309

OC中继承子类对象调用方法机制 子类对象访问父类中的实例变量

在继承中,子类对象如何调用到正确方法的机制        每一个Objective - C对象都有一个隐藏的指针指向类的代码,当向一个对象发送消息的时候,当前的对象会首先在当前类里去查找相应的方法,如果找到的话,直接执行代码;若没有找到,则去父类里找对应的方法,如果找到的话,就会执行。如果找不到继续按照这样的原则,沿着继承链向上查找,直到根类NSObject(这个类是Objective -

ysxr001的专栏 2810

子类重写父类变量_为什么在子类中不重写超类的实例变量

子类重写父类变量 当我们在父类和子类中创建一个具有相同名称的变量,并尝试使用持有子类对象的父类引用访问它时,我们会得到什么? 为了理解这一点,让我们考虑下面的示例,在该示例中,我们在Parent和Child类中都声明了一个具有相同名称的变量x 。 class Parent { // Declaring instance variable by name `x` Strin...

最佳 Java 编程 1453

对父类 对象=new 子类的理解

父类new子类

weixin_63785984的博客 1294

Day01_11目标:继承_super访问父类方法

目标:继承_super访问父类方法 可以在子类的实例方法中通过super去访问父类的被重写的方法。 public class TestDemo { public static void main(String[] args) { Cat ddm = new Cat(); ddm.go(); } } // 父类 class Animal{ p...

Dream丶Chaser的博客 165

java-子类方法重写规则

记录自己的学习理解,有不对,不足的地方希望前辈补充。 ***(一)重写语法规则 :子类在继承了父类的某个方法之后,如果想要重写这个方法,则需要创建一个与父类方法的返回类型一样,名字一样,参数个数一样的方法,且访问权限大于等于父类的方法。这样子类中定义的方法就是方法重写(理解为对父类继承而来方法进行改造,具体改造成什么样看个人项目需求。)。子类中方法重写后,子类对象调用的则是重写后的方法,父类的方法也被隐藏,如果子类想要调用父类的那个方法则需要使用super。 **注意:**在JDK1.5之后,如果一个子类F

m0_51668628的博客 2792

子类重写父类方法时权限修饰符的关系

子类在重写父类方法时,必须拥有不小于父类的权限。 例如如下示例: public class TestPriority { protected int method1(int a, int b){ return 0; } } class A extends TestPriority{ private int method1(int a, int b){ return 0; } } 这个时候编译出错,提示 'method1(i.

远方的少年 2297

php子类与父类关系,父类与子类 - PHP网络课程 - php中文网博客

创建父类和子类,子类加载父类:父类代码:实例/***创建手机类:MobilePhone*/classMobilePhone{//public$brand;protected$brand;protected$model;//private$price;protected$price;//构造方法publicfunction__construct($brand,$mo...

weixin_39622587的博客 232

2. 继承 子类的重写

4.在子类构造方法中,第一行默认有super();语句,该语句用于调用父类构造方法。2.子类会调用重写之后的方法,如果要调用父类中的方法,使用super.方法名();1.在子类里声明一个和父类相同的方法,并且可以重新定义方法体。3.当子类中声明了和父类中同名的属性。调用父类中其他重载的构造方法。3.创建子类对象时,会默认调用父类的无参构造方法。1.子类通过extends关键字继承父类。2.使用super.属性访问父类中的属性。2.子类可以继承父类非私有属性。子类SmartPhone类。......

qq_58731454的博客 321
下一篇: 一、java基础知识(oop以前)
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值