java学习之类的继承

本文详细介绍了Java中类的继承概念,包括如何使用extends关键字实现继承,以及继承后的属性和行为调用。通过具体代码示例,展示了父类字段和方法的访问方式,构造方法的调用顺序,以及this和super关键字的应用。同时,文章还提供了构造方法调用顺序的实例,帮助读者理解子类构造方法如何调用父类构造方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类的继承,

  1. 继承的语法格式extends关键字继承的是属性和行为
  2. 代码示例,调用父类里的字段和方法
  3. 构造方法的调用顺序,以及this关键字和super关键字的使用

  4. 代码参考教材java程序设计胡平老师主编(侵删)

     

  5. package ch06;
    
    	class Father {
    		protected int m=2;
    		private int n=4;
    		public Father() {//无参数的构造方法
    
    		}
    		public Father(String s) {//有参数的构造方法
    
    		}
    		public void methodA() {//公有的方法a
    			System.out.println("调用的是公有方法a");
    		}
    		void methodB() {//默认的方法b
    
    		}
    		private void methodC() {//私有函数c
    
    		}
    		public void testFather(Father f) {//公有的测试函数
    
    		}
    
    	}
    
    	class Son extends Father{
    		public void testSon(Son s) {
    
    		}
    		public static void main(String[] args) {
    			// TODO Auto-generated method stub
    			Son S1=new Son();
    			System.out.println(S1.m);
    			S1.toString();
    			S1.methodA();
    			S1.methodB();
    			S1.testFather(S1);
    			Father f =new Father();
    
    		}
    	}
    	
    
    package test1;//构造方法的调用顺序先调用父类的构造方法,
    
     class Food1 {//食物类
    
    }
    class Fruit extends Food1{//水果继承了食物类里面的方法和属性这里为空
    	Fruit(){
    		System.out.println("Fruit()");//没有参数的构造方法
    	}
    	Fruit(String color){//有一个参数的构造方法
    		System.out.println("Fruit(String)");
    	}
    }
    class Apple extends Fruit{//子类继承水果类
    	Apple(){
    		System.out.println("Apple()");
    	}
    	Apple(String color){
    		this(color,0);
    		System.out.println("Apple(String)");
    		
    	}
    	Apple(String color,int count){
    		super(color);
    		System.out.println("Apple(String,int)");
    	}
    }
    
    public class Food{
    	public static void main(String[] args) {
    		Apple a1=new Apple();
    		System.out.println();
    		Apple a2=new Apple("red");
    		System.out.println();
    		Apple a3=new Apple ("green,10");
    	}
    }

    演示结果

  6. Fruit()
    Apple()

    Fruit(String)
    Apple(String,int)
    Apple(String)

    Fruit(String)
    Apple(String,int)
    Apple(String)
     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值